4

Currently on my webpage I have a timer that runs a function every 30 seconds:

setInterval("someFunction(userId)", 30000);   

This works fine, but the problem is if 100's of users leave their browser open (say when they go for lunch), it will poll our system and increase the load on our servers for no reason.

How can I stop this timer from running after say 20 minutes?

loyalflow
  • 14,275
  • 27
  • 107
  • 168

4 Answers4

14

Just set timeout for 20 minutes to clear the interval:

var interval = setInterval(function() {
    someFunction(userId);
}, 30000);

setTimeout(function() {
    clearInterval(interval);
}, 1000 * 60 * 20);
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 2
    I suggest to incorporate event listeners in the code, because otherwise the code just stops running after 20 minutes, even if the user is actively using the site. – Rob W Oct 17 '12 at 16:15
2

When you call setInterval, you get a value returned, which is a handle to the running interval.

So the solution is to schedule another closure, which will prevent this interval from running:

var interval = setInterval("someFunction(userId)", 30000);  
setTimeout(function(){ clearInterval(interval) }, 20 * 60 * 1000);
Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
0

Set your interval as a variable.

Set another timer to reset that interval, or set a disable flag for your polling script after 20mins.

Bryan Allo
  • 696
  • 3
  • 9
0

Try this:

var intervalId= setInterval(function(){
   someFunction(userId);
 }, 30000); 

setTimeout(function(){
   clearInterval(intervalId);
},20*60*1000);

setInterval returns an intervalId that you can use to pass to clearInterval later on.

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486