Reputation: 2257
In several places in our code we do something like this:
eventGrabber.poller = setInterval(grabEvents, 50);
to call the grabEvents method every 50 ms. However, since we do it in more than one place I am wondering if grabEvents is being called more often then every 50ms. In other words if I did this:
eventGrabber.poller = setInterval(grabEvents, 50);
//wait 25 ms here
eventGrabber.poller = setInterval(grabEvents, 50);
Would there now be two timers running calling grabEvents every 25 ms (one of which we could never stop because we lost its handle)?
Would changing all of our calls to something like this solve this problem (if it really is a problem):
//if there is a timer running clear it out first
clearInterval(eventGrabber.poller); //if poller is null does it matter??
//now start the timer
eventGrabber.poller = setInterval(grabEvents, 50);
Upvotes: 4
Views: 2192
Reputation: 7067
Yes you would have multiple intervals running, what if you encapsulate it and do something like this:
function poller(callback, ms) {
var interval
return {
start: function() {
if (!interval) {
interval = setInterval(callback, ms)
}
},
stop: function() {
clearInterval(interval)
}
}
}
eventGrabber.poller = poller(grabEvents, 50)
eventGrabber.poller.start()
// ......
eventGrabber.poller.start()
This way you can be sure it won't run more than once :)
Upvotes: 1
Reputation: 82287
Yes there would be two intervals running at that point. However, the "handle" is really nothing but an integer. Using clearInterval expects a number as an argument, however, if it is passed NaN, undefined, null, etc. it will just silently fail and move on.
I would suggest screening for the poller and clearing it as suggested at the end of your question. That is probably best practice.
Depending on how many timers you have on your page, you can always wipe out every one of them. Although, this may not be desired depending on if there are active intervals that are critical to the page's operation.
var maxInterval = setInterval(function(){},10000);
for(var i = 0; i <= maxInterval; i++) clearInterval(i);
Upvotes: 2