How to clear interval and set it again?

This is what i am trying to accomplish: when the last slide is reached fadeOut last slide and then fadeIn first slide, and then clearInterval (everything works with this part). Now my problem is that i want to setInterval again if it doesn't exists but I don't know how to make it happen:(
I have tried to solve this with if statment but then my script doesn't work at all!
So how can I RESTART my interval again? THANK YOU!!
Without if statement like this it's working fine:

if(!intervalID){
    intervalID = setInterval(animate,5000);
}    

This is what I have so far:

$(document).ready(function() {
  /*check if intervalID don't exists messes UP!!*/
  if (!intervalID) {
    intervalID = setInterval(animate, 5000);
  }

  //Hide everything except first slide and controls

  $('.slidewrap div:not(.slidewrap div:first,.slidewrap .slide_controls)').hide();

  var animate = function() {

    /*if .pagination_active is last removeClass and addClass to .pagination_active 
             first li tag*/

    if ($('.pagination_active').is($('.slide_controls ul li:last'))) {
      $('.pagination_active').removeClass('pagination_active');
      $('.slide_controls ul li:first').addClass('pagination_active');
    } else {
      $('.pagination_active').removeClass('pagination_active').next().addClass('pagination_active');
    }

    /*if div.active is last fadeOut and add .active class 
             to the first div and fadeIn FIRST div then CLEAR INTERVAL and set intervalID to zero */

    if ($('.active').is($('.slidewrap div:last'))) {
      $('.active').fadeOut(1000).removeClass('active');
      $('.slidewrap div:first').addClass('active').fadeIn(1000, function() {
        clearInterval(intervalID);
        intervalID = 0;

      });
    }

    //OR .active fadeOut and next div fadeIn
    else {
      $('.active').fadeOut(1000).next().fadeIn(1000, function() {
        $('.slidewrap div.active').removeClass('active').next('div').addClass('active');

      });
    }

  }

  var intervalID;
  intervalID = setInterval(animate, 3000);

});

Answers:

Answer

After clear an interval you need to start it again with setInterval().

It would be better to make function for your setInterval()

var intervalID = null;

function intervalManager(flag, animate, time) {
   if(flag)
     intervalID =  setInterval(animate, time);
   else
     clearInterval(intervalID);
}

Here flag is a boolean variable with value true/ false. true will execute setInterval() and false will clearInterval();

Now you can use above function as you need.

For example:

intervalManager(true, animate, 300);  // for setInterval

intervalManager(false);  // for clearInterval
Answer

Here is utility object that takes a callback and interval which you can use to start and stop an interval.

   //simple utility object to start and stop an interval       
    var IntervalUtil = function(functionCall, interval){


        var intervalObj = 0,
            INTERVAL    = interval;

        var callback = functionCall;

        function startTimer(){
            console.log('start timer', intervalObj)
            if(intervalObj === 0){
                intervalObj = setInterval(callback, INTERVAL)
            }
        }   

        function stopTimer(){
            clearInterval(intervalObj);
            intervalObj = 0;
            console.log('timer stopped', intervalObj);
        }

        return {
            startTimer : startTimer,
            stopTimer  : stopTimer
        }

    };  

*You would use it like so *

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    <meta name="author" content=""/>

    <title>Timer : setInterval()</title> 


    <style type="text/css">


    html, body, div, span, applet, object, iframe,
    h1, h2, h3, h4, h5, h6, p, blockquote, pre,
    a, abbr, acronym, address, big, cite, code,
    del, dfn, em, img, ins, kbd, q, s, samp,
    small, strike, strong, sub, sup, tt, var,
    b, u, i, center,
    dl, dt, dd, ol, ul, li,
    fieldset, form, label, legend,
    table, caption, tbody, tfoot, thead, tr, th, td,
    article, aside, canvas, details, embed, 
    figure, figcaption, footer, header, hgroup, 
    menu, nav, output, ruby, section, summary,
    time, mark, audio, video {
        margin: 0;
        padding: 0;
        border: 0;
        font-size: 100%;
        color:#000;
        line-height:1.3em;
        font: inherit;
        vertical-align: middle;
        font-family:arial;
        font-size:12px;
        outline:none;
    }

    a{
        outline:none;
        text-decoration:none;
        color:#145486;
    }
    a span{
        color:#145486;
    }

    h1{
        font-weight:normal;
        font-size:32px;
    }

    body{
        background:#efefef;
        text-align:center;
    }
    .content{
        width:400px;
        padding:20px;
        margin:10px auto;
        background:#fff;
        border:solid 1px #ebebeb;
        text-align:left;
    }

    #toggleTimer{
        color:#fff;
        font-size:10px;
        padding:2px 7px;
        display:inline-block;
        background:#357cb7;
        border:solid 1px #0c8af4;
    }

    #toggleTimer.running{
        background:#f14621;
        border:solid 1px #ff4c00;
    }

    #output{
        padding:7px;
        font-size:10px;
        border:dashed 1px #ebebeb;
        background:#f8f8f8;
        margin-left:10px;
        display:inline-block;
    }
    em{
        font-weight:bold;
    }

    </style>

</head>
<body>


<div class="content">

    <h1>Set Interval Code</h1>

    <a href="javascript:" id="toggleTimer" class="">Start Timer</a>

    <span id="output"></span>

    <br class="clear"/>

</div>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>


<script type="text/javascript">

    $(document).ready(function(){
        var demo = new Demo();
    });


    var Demo = function(){

        var self = this;

        var START_TEXT = "Start Timer",
            STOP_TEXT  = "Stop Timer";

        var $toggle = $('#toggleTimer'),
            $output = $('#output');

        var count = 0;

        var intervalUtil;

        function init(){
            intervalUtil = new IntervalUtil(printMessage, 1000);
            setClickHandler();
            return self;
        }   

        function setClickHandler(){
            $toggle.click(toggleTimer)
        }

        function toggleTimer(){

            $toggle.toggleClass('running');

            if($toggle.hasClass('running')){
                $toggle.text(STOP_TEXT);
                intervalUtil.startTimer();
            }else{
                $toggle.text(START_TEXT);
                intervalUtil.stopTimer();
            }
        }

        function printMessage(){        
            $output.html("printMessage called <em>" + (count++) + "</em> times");
        }

        return init();

    }


    //simple utility object to start and stop an interval       
    var IntervalUtil = function(functionCall, interval){


        var intervalObj = 0,
            INTERVAL    = interval;

        var callback = functionCall;

        function startTimer(){
            console.log('start timer', intervalObj)
            if(intervalObj === 0){
                intervalObj = setInterval(callback, INTERVAL)
            }
        }   

        function stopTimer(){
            clearInterval(intervalObj);
            intervalObj = 0;
            console.log('timer stopped', intervalObj);
        }

        return {
            startTimer : startTimer,
            stopTimer  : stopTimer
        }

    };  

</script>


</body>
</html>
Answer

Just Example

var myVar 
function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
    clearInterval(myVar);
}
function myStartFunction() {
    myVar = setInterval(myTimer, 1000);
}
myStartFunction();
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>
<button onclick="myStartFunction()">Start time</button>

Answer

Wrap setInterval in a function, for example:

const startTimer = (timer) => {
    let seconds = 10
    timer = setInterval(() => {
        console.log(seconds)
        seconds--
        if(seconds === 0) {
            console.log("Time's up")
            clearInterval(timer)
        }
    }, 1000)
}

and call it wherever you want:

startTimer()

Answer

Solution for timer which counts 15 sec then goes to main page, if there is click on screen resets timer to the start. It may be useful to someone. (x is counter for touch events) :

  var productInterval = null;
  var counterForGoToMainPage = 15;

  function startTimer(){
    counterForGoToMainPage--;

    if(counterForGoToMainPage == 0){
      clearInterval(productInterval);
      counterForGoToMainPage = 15;
      window.location.href = "/";
      }
  }

  function countTouches(event) {
  var x = event.touches.length;

    if(x == 1) { 
      clearInterval(productInterval);
      counterForGoToMainPage = 15;
      productInterval = setInterval(function(){
         startTimer();
      },1000);
    }
  }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.