Disabling setInterval - not sure if this is an alternative to clearInterval

449 views Asked by At

So I know that you can assign setInterval to a variable, and later pass that variable to clearInterval to disable the timer.

What I'm wondering:

Say I have a global variable that is null on page initiation. When a specific function gets called then the global variable is assigned setInterval(fname, seconds). When I don't want this interval running anymore, I set the global variable to null.

For what I'm specifically testing (a sequence of images being rendered one after the other) it seems to work, but I wonder if I'm making some sneaky error.

Here's an overview of my code:

MyStuff.controls = {};
MyStuff.controls.animation_timer = null;

MyStuff.controls.start = function () {
    if (!MyStuff.controls.animation_timer) {
         MyStuff.controls.animation_timer = setInterval(MyStuff.controls.animate, 500);
    }
}

MyStuff.controls.stop = function () {
    MyStuff.controls.animation_timer = null;
}
3

There are 3 answers

0
pickle On

I made a mistake. I was calling clearInterval I just didn't see it for whatever reason - the example I presented won't work. Sorry everyone!

0
Bergi On

When I don't want this interval running anymore, I set the global variable to null.

No, that does not work. You can simply try out your code. It will continue executing your callback, even if you've thrown away the identifier that could have been used to stop the interval.

Just call clearInterval:

MyStuff.controls.stop = function () {
    clearInterval(MyStuff.controls.animation_timer);
    MyStuff.controls.animation_timer = null;
}
1
Mr. Llama On

Does your example work? Sure, I don't see why not.

Is it good form? Probably not. You're still going to be calling MyStuff.controls.animate on a regular basis but it'll simply do nothing (assuming it's watching and acts conditionally to the global variable). That's wasted processing right there. Here's an example of what that would look like. Check your console for the output. You can see that the function still runs, it just behaves differently.

I can't think of a good reason to not use setInterval/clearInterval.

If you need to ensure that only one instance is running, simply treat the global variable as a mutex. For example:

  • When you want to start the interval, check if the global variable. If it's null, run setInterval and store the result in the global variable. If it's non-null, the interval is already running, so don't call setInterval.
  • When you want to stop the interval, use clearInterval on the global variable, then set it to null.