Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval with loop time

setInterval(function(){}, 200) 

this code run the function each 200 miliseconds, how do I do it if I only want the function to be ran 10 times.

thanks for help.

like image 577
bingjie2680 Avatar asked Dec 07 '11 20:12

bingjie2680


People also ask

Is setInterval a loop?

setInterval() simply put, is a timed loop.

How do you set an interval timer?

The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.

How do you break a setInterval loop?

Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.

Does setInterval repeat?

Yes, setInterval repeats until you call clearInterval with the interval to stop.


2 Answers

Use a counter which increments each time the callback gets executed, and when it reaches your desired number of executions, use clearInterval() to kill the timer:

var counter = 0; var i = setInterval(function(){     // do your thing      counter++;     if(counter === 10) {         clearInterval(i);     } }, 200); 
like image 190
karim79 Avatar answered Sep 28 '22 00:09

karim79


(function(){ var i = 10;     (function k(){          // your code here                      if( --i ) {         setTimeout( k, 200 );         }      })() })() 
like image 22
Esailija Avatar answered Sep 28 '22 01:09

Esailija