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?
Just set timeout for 20 minutes to clear the interval:
var interval = setInterval(function() {
someFunction(userId);
}, 30000);
setTimeout(function() {
clearInterval(interval);
}, 1000 * 60 * 20);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With