Ad

Interval Keeps Firing Even Though ClearInterval Has Been Called

I am trying to get a function to run 10 times with a pause inbetween each run, yet when I try to it repeats the function infinite times then after 10 times it pauses, and so on. Right now this is the code with the problem:

for(i=0;i<10;i++) {
    console.log(i);
    interval = setInterval(function() {console.log("Function ran");}, 1000);
}
window.clearInterval(interval);

Console:
0
1
2
3
4
5
6
7
8
9
Function ran

["Function ran" is repeated infinite times after "9"]

Ad

Answer

interval = setInterval(function() {console.log("Function ran");}, 1000);

This line creates a new interval-instance each time, which means you have created 10 intervals. At the end of the loop interval holds the id of the last interval that was created. Hence that's the only one you're clearing, and the other ones are still running.

To cancel the interval, you need to keep track of how many times the function has been invoked. One way you can do that is as follows:

function pauseAndRepeat(delay, iterations, func) {
    var i = 0;
    var interval = setInterval(function() {
        func();
        if(++i === iterations) {
            clearInterval(interval);
        }
    }, delay);    
}

Here we have a function that defines a counter (i) in its local scope. Then it creates an interval using a function that checks the counter to see if it should call your function (func) or clear the interval when it is done. interval will have been set when the interval-handler is actually called. In this case the handler is basically a closure since it is bound to the local scope of pauseAndRepeat.

Then you can invoke the function as follows:

pauseAndRepeat(1000, 10, function() {
    console.log("Function ran");
});

This will print out Function ran ten times, pausing for a second each time.

Ad
source: stackoverflow.com
Ad