Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the method executed immediately when I use setTimeout?

I'm trying to write a simple code with a setTimeout, but the setTimeout just won't wait the time it's supposes to and the code execute immediately. What am I doing wrong?

setTimeout(testfunction(), 2000); 
like image 214
Adler Avatar asked Aug 21 '11 09:08

Adler


People also ask

Why is setTimeout called immediately?

Keeping the parentheses invokes the function immediately. The reason is that the first argument to setTimeout should be a function reference, not the return value of the function. So the correct code is, setTimeout(Func1, 2000);

Why is setTimeout executed at last?

setTimeout schedules the function for execution. That scheduler doesn't do its thing until after the current thread yields control back to the browser, e.g. after the last logging statement has executed.

Does set timeout stop execution?

No, setTimeout does not pause execution of other code.

How do you wait for setTimeout to finish?

Use of setTimeout() function: In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds. Use of async or await() function: This method can be used if the exact time required in setTimeout() cannot be specified.


2 Answers

You're calling the function immediately and scheduling its return value.

Use:

setTimeout(testFunction, 2000);                        ^ 

Notice: no parens.

like image 110
Mat Avatar answered Sep 20 '22 06:09

Mat


Remove the parenthesis

setTimeout(testfunction(), 2000); 

If you want to send parameters to the function, you can create an anonymous function which will then call your desired function.

setTimeout(function() {      testfunction('hello');  }, 2000); 

Edit

Someone suggested to send a string as the first parameter of setTimeout. I would suggest not to follow this and never send a string as a setTimeout first parameter, cause the eval function will be used. This is bad practice and should be avoided if possible.

like image 28
Jose Faeti Avatar answered Sep 24 '22 06:09

Jose Faeti