"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Execute a JavaScript Script After a Specified Delay?

How to Execute a JavaScript Script After a Specified Delay?

Published on 2024-11-19
Browse:842

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:

function myFunction() {
  // Code to execute after the delay
}

setTimeout(myFunction, 2000); // Execute "myFunction" after 2 seconds

Using Anonymous Functions for Parameter Passing

If you want to call a function with a parameter, you can use an anonymous function:

var a = "world";
setTimeout(function(){alert("Hello "   a)}, 2000);

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:

function callback(a){
    return function(){
        alert("Hello "   a);
    }
}

var a = "world";
setTimeout(callback(a), 2000);
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3