Javascript - telling setInterval to only fire x amount of times?

Is it possible to limit the amount of times that setInterval will fire in javascript?


Solution 1:

You can call clearInterval() after x calls:

var x = 0;
var intervalID = setInterval(function () {

   // Your logic here

   if (++x === 5) {
       window.clearInterval(intervalID);
   }
}, 1000);

To avoid global variables, an improvement of the above would be:

function setIntervalX(callback, delay, repetitions) {
    var x = 0;
    var intervalID = window.setInterval(function () {

       callback();

       if (++x === repetitions) {
           window.clearInterval(intervalID);
       }
    }, delay);
}

Then you can call the new setInvervalX() function as follows:

// This will be repeated 5 times with 1 second intervals:
setIntervalX(function () {
    // Your logic here
}, 1000, 5);

Solution 2:

I personally prefer to use setTimeout() spaced out to achieve the same effect

// Set a function to run every "interval" seconds a total of "x" times
var x = 10;
var interval = 1000;

for (var i = 0; i < x; i++) {
    setTimeout(function () {
        // Do Something
    }, i * interval)
}

There's no clean up required with clearInterval()

You can enclose it to avoid variables leaking and it looks pretty clean :)

// Definition
function setIntervalLimited(callback, interval, x) {

    for (var i = 0; i < x; i++) {
        setTimeout(callback, i * interval);
    }

}

// Usage
setIntervalLimited(function() {
    console.log('hit');          // => hit...hit...etc (every second, stops after 10)
}, 1000, 10)