Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start setInterval loop immediately? [duplicate]

In a simple setInterval

setInterval(function() {       // Do something every 9 seconds }, 9000); 

The first action will happen after 9 seconds (t=9s). How to force the loop to perform the first action immediately (t=0)?

I think it is due to the mechanism of setInterval to have Delay - Action - Delay - Action ... loop; instead of Action - Delay - Action - Delay ... loop.

EDIT: My function is indeed a loop as

setInterval(function(){ $('.test').each(function(idx){     var duration = 1000;     $(this).delay(duration*idx);     Some stuff here }); }, 4000); 
like image 454
Googlebot Avatar asked May 12 '12 11:05

Googlebot


People also ask

How do you run setInterval immediately?

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.

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.

Can you clearInterval within setInterval?

Calling clearInterval() inside setInterval() has no effect But after calling clearInterval(), it will continue to execute.

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.


1 Answers

Keep it simple. You can use a named function instead of an anonymous function; call it and set an interval for it.

function doSomething() {     console.log("tick"); } doSomething(); setInterval(doSomething, 9000); 

Create a scope if necessary:

(function() {     function doSomething() {         console.log("tick");     }     doSomething();     setInterval(doSomething, 9000); })(); 

Finally, the following works without creating or affecting x:

setInterval(function x() {     console.log("tick");     return x; }(), 9000); 
like image 67
Salman A Avatar answered Sep 29 '22 04:09

Salman A