JavaScript provides a method called setTimeout that allows you to delay the execution of a script. Unlike jQuery's delay() or wait(), setTimeout works asynchronously.
Using setTimeout with a Function:
If you want to call a named function after a delay, you can use bracket notation:
<code class="js">setTimeout(functionName, delayInMilliseconds);</code>
Passing Parameters with an Anonymous Function:
However, if you need to pass parameters to the function, you must use an anonymous function enclosed in parentheses:
<code class="js">setTimeout(function() { alert("Hello " + parameter); }, delayInMilliseconds);</code>
Dealing with Variable Changes:
Note that setTimeout uses the value of variables at the time the function is passed. To ensure the correct value is used, you can wrap the parameter in a callback function:
<code class="js">function callback(parameter) { return function() { alert("Hello " + parameter); } } let parameter = "world"; setTimeout(callback(parameter), delayInMilliseconds);</code>
The above is the detailed content of How to Use setTimeout for Delayed JavaScript Execution?. For more information, please follow other related articles on the PHP Chinese website!