Is it possible to limit the amount of times that setInterval will fire in javascript?
+7
A:
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 every for 5 times with 1 second intervals:
setIntervalX(function () {
// Your logic here
}, 1000, 5);
Daniel Vassallo
2010-06-02 10:54:35
Bah. You beat me by seconds, and did the same get-a-short-answer-in-and-then-expand-on-it trick :)
Tim Down
2010-06-02 11:07:59
@Tim: Yep, I was twice lucky as the fastest-gun today :) Doesn't happen very often.
Daniel Vassallo
2010-06-02 11:17:45
+1
A:
No you have to set a timeout that call a clearInterval. This should works:
function setTimedInterval(callback, delay, timeout){
var id=window.setInterval(callback, delay);
window.setTimeout(function(){
window.clearInterval(id);
}, timeout);
}
blow
2010-06-02 10:57:14
@T.J. Sometimes I find the opposite more freaky: When we post many different solutions for one trivial problem!
Daniel Vassallo
2010-06-02 11:05:28
@T.J. Crowder: Strange you using local variables and anonymous functions ;)
stagas
2010-06-02 11:06:04
@stagas: LOL! Sometimes for brevity in examples, I've been known...
T.J. Crowder
2010-06-02 12:04:24
A:
This will clear the interval after 10 calls
<html>
<body>
<input type="text" id="clock" />
<script language=javascript>
var numOfCalls = 0;
var int=self.setInterval("clock()",1000);
function clock()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("clock").value=t;
numOfCalls++;
if(numOfCalls == 10)
window.clearInterval(int);
}
</script>
</form>
</body>
</html>
Amr ElGarhy
2010-06-02 10:58:39