Is it possible to limit the amount of times that setInterval will fire in javascript?
To stop it after running a set number of times, just add a counter to the interval, then when it reached that number clear it.
“setinterval for 5 times” Code Answer'svar intervalID = setInterval(alert, 1000); // Will alert every second. // clearInterval(intervalID); // Will clear the timer. setTimeout(alert, 1000); // Will alert once, after a second.
Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set with the required callback.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With