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

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);

Leave a Comment