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);
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