April 29, 2012

How can I resume setInterval after clearInterval has been called in javascript?

Question by Hcabnettek

I have this code which works ok but I would like to stop polling and clearInterval if the user is inactive (no mouse move) after say 5 iterations rather than be in a continuous loop.

var i, active = new Date, iter = 1;

$(window).on('mousemove', function(e){
active = new Date;          
});

i = setInterval(function(){
    if(new Date().getTime() - active.getTime() < 1000){
     console.log("sending active event to server.....");
             iter = 1;  
    else{
      iter++;
        if(iter >= 5){
           clearInterval(i);
        }
     }          
}, 2000);   

right now it checks every two seconds in this example. I would like to check the active date say 5 times and if its expired 5 iterations in a row, call clearInterval(i)… so something inside the mousemove callback should reinitialize the setInterval only if it’s currently not running. How can I accomplish this? Thanks for any tips and samples. I’d like to keep using an anonymous function if possible.

Answer by Starx

Seperate the Interval function

function intFunc(){
    if(new Date().getTime() - active.getTime() < 1000){
     console.log("sending active event to server.....");
             iter = 1;  
    else{
      iter++;
        if(iter >= 5){
           clearInterval(i);
        }
     }          
};

Now, call them on the two places you need

var i;
$(window).on('mousemove', function(e){
  active = new Date;          
  i = setInterval(intFunc, 2000);

});
i = setInterval(intFunc, 2000);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!