SiteCrafting, Inc.
2 Apr
The Multiple Interval JavaScript Problem
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).
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);}
Coding Techniques, From the Workbench, Javascript
by Paul Sayre | 4/2/2009 12:39pm | Comments (1)
by Paul Sayre | 4/2/2009 12:39pm | Comments (1)
Nice. Worked for me with pausing intervals in IE9.
Left by Sabrina | Apr 29, 2011