The Multiple Interval JavaScript Problem
The Phantom Menace
Using intervals in JavaScript for pausing/unpausing events can sometimes cause a phantom interval which you can't control. Learn how to stop that phantom in it's tracks with one line of code.I just spent about 30 minutes trying to debug a problem in JavaScript. The setup is an Ajax call that is made at a tick rate. You can pause the ticks, which I implemented by clearing the interval (JavaScript's version of a timer).
var interval;
function paused() {clearInterval(interval);
}
function unpause() { interval = setInterval(doSomething, timeout);}
This is some fairly common code found on the net. The problem comes when you double click the unpause button. It will create an extra interval which the pause does not stop. There is, however, a very simple solution. If you clear the previous interval before starting a new one, then there will be no running intervals which have no variable. It looks something like this:
var interval;
function paused() {clearInterval(interval);
}
function unpause() {clearInterval(interval);
interval = setInterval(doSomething, timeout);}



Add your comment below
Leave a Comment