Home > Web Front-end > JS Tutorial > How to Execute a JavaScript Script After a Specified Delay?

How to Execute a JavaScript Script After a Specified Delay?

DDD
Release: 2024-11-01 02:11:28
Original
739 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template