tags:

views:

106

answers:

3

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
Bah. You beat me by seconds, and did the same get-a-short-answer-in-and-then-expand-on-it trick :)
Tim Down
@Tim: Yep, I was twice lucky as the fastest-gun today :) Doesn't happen very often.
Daniel Vassallo
+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
Wow, my answer 13 seconds later was virtualy *identical*. Freaky.
T.J. Crowder
@T.J. Sometimes I find the opposite more freaky: When we post many different solutions for one trivial problem!
Daniel Vassallo
@T.J. Crowder: Strange you using local variables and anonymous functions ;)
stagas
@stagas: LOL! Sometimes for brevity in examples, I've been known...
T.J. Crowder
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