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);
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);
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.
No, setTimeout does not pause execution of other code.
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.
You're calling the function immediately and scheduling its return value.
Use:
setTimeout(testFunction, 2000); ^
Notice: no parens.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With