Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
17

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

[#96610] Sunday, May 30, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
laytonlamontm

Total Points: 745
Total Questions: 130
Total Answers: 130

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
;