Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set an interval, but then stop it after 20 minutes

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?

like image 439
loyalflow Avatar asked Dec 07 '22 11:12

loyalflow


2 Answers

Just set timeout for 20 minutes to clear the interval:

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

setTimeout(function() {
    clearInterval(interval);
}, 1000 * 60 * 20);
like image 53
VisioN Avatar answered Dec 11 '22 11:12

VisioN


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);
like image 20
Andrzej Doyle Avatar answered Dec 11 '22 09:12

Andrzej Doyle