Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - telling setInterval to only fire x amount of times?

Tags:

javascript

Is it possible to limit the amount of times that setInterval will fire in javascript?

like image 221
Probocop Avatar asked Jun 02 '10 10:06

Probocop


People also ask

How do you stop setInterval after output is given 10 times?

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.

How do you run setInterval 5 times?

“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.

Does setInterval fire right away?

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.


2 Answers

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); 
like image 164
Daniel Vassallo Avatar answered Sep 21 '22 10:09

Daniel Vassallo


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) 
like image 41
NDavis Avatar answered Sep 21 '22 10:09

NDavis