Home >Web Front-end >JS Tutorial >How to Execute a JavaScript Script After a Specified Delay?
Execute Script after Specified Delay Using JavaScript
Executing a script after a specific delay is a common task in JavaScript. To do this, you can leverage the setTimeout() method.
Unlike jQuery's delay() or wait(), setTimeout() accepts a function as its first parameter. This function is what you want to execute after the delay. The second parameter specifies the delay in milliseconds.
Using Named Functions for Delay
The following code demonstrates how to call a function with a delay using a named function:
<code class="javascript">function myFunction() { // Code to execute after the delay } setTimeout(myFunction, 2000); // Execute "myFunction" after 2 seconds</code>
Using Anonymous Functions for Parameter Passing
If you want to call a function with a parameter, you can use an anonymous function:
<code class="javascript">var a = "world"; setTimeout(function(){alert("Hello " + a)}, 2000);</code>
However, this can lead to issues if the value of a changes before the delay expires. To preserve the original value, you can wrap the anonymous function in another function that takes a as an argument:
<code class="javascript">function callback(a){ return function(){ alert("Hello " + a); } } var a = "world"; setTimeout(callback(a), 2000);</code>
The above is the detailed content of How to Execute a JavaScript Script After a Specified Delay?. For more information, please follow other related articles on the PHP Chinese website!