174
rated 0 times
[
181]
[
7]
/ answers: 1 / hits: 84434
/ 14 Years ago, wed, june 2, 2010, 12:00:00
Is it possible to limit the amount of times that setInterval will fire in javascript?
More From » javascript
Is it possible to limit the amount of times that setInterval will fire in javascript?
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);