Aaron
Aaron

Reputation: 11673

Is it possible to call a clearInterval method on a setInterval variable that is out of scope?

I have a setInterval function that is initializing a varibale with it's id in a for loop, which results in a number of setInterval functions executing in the for loop. Each of the setInterval functions will be assigned to a variable now my question is, is it possible for one single variable to contain the values of all of the setIntervals id's or only one? If all of the id's can all be contained in a single variable is it possible to clear certain setIntervals via there id that is contained in the variable or will I need to declare a unique variable for each setInterval to be able to do this?

var intervalId;
for(var i = 0; i < 10; i++) {
     intervalId = setInterval(function() {}, 100);
}

Upvotes: 1

Views: 161

Answers (1)

Pointy
Pointy

Reputation: 413720

The values returned from setInterval and setTimeout are numbers, so only one will "fit" in a variable.

You could make an array:

var intervalId = [];
for(var i = 0; i < 10; i++) {
     intervalId.push( setInterval(function() { ... }, 100) );
}

Note that there's something important missing from your question, and that's the code in the interval function. Specifically, if that code wants to refer to "i", there's a problem: all of the separate functions will share the same "i" variable (the one declared in the loop header).

To get around that, you could do this:

 function makeTimerFunction(i) {
   return function() {
     // the code
     if (whatever) { clearInterval(intervalId[i]); }
     // and so on
   };
 }

 var intervalId = [];
 for (var i = 0; i < 10; i++) 
   intervalId.push( setInterval( makeTimerFunction(i), 100 ) );

By using a separate function, you create another scope and can "freeze" each value of "i" in a separate, per-timer variable.

edit — @pst points out correctly that if it is really the case that you do want to refer to the timer id from inside the handler functions, then there's really no need for that "intervalId" array at all - you could just use the wrapper function to isolate the call to setInterval().

function createTimer() {
  var timerId = setInterval(function() {
    // the code
    if (whatever) { clearInterval( timerId ); }
    // ...
  };
}

for (var i = 0; i < 10; ++i)
  createTimer();

That way each timer is set up with it's own private timer ID variable. Of course, if you do need the timer id outside the function, then you need an external cache for the ids.

Upvotes: 4

Related Questions