Execute Script After Specific Delay Using JavaScript
When seeking a JavaScript method analogous to jQuery's "delay()" or "wait()" functions, which allow for delayed script execution, "setTimeout()" emerged as a reliable solution.
However, when it comes to invoking a function with a parameter at a later time, anonymous function calls must be utilized.
While it's tempting to pass a function as an argument for later invocation by omitting the brackets after its name, this approach has a caveat:
var a = "world"; setTimeout(alert("Hello" + a), 2000); // Displays "Hello world" immediately
To ensure delayed execution, either use a function name (as demonstrated by Flubba) or an anonymous function, particularly when passing a parameter:
var a = "world"; setTimeout(function() { alert("Hello" + a); }, 2000); // Displays "Hello world" after 2 seconds
However, this alternative has a limitation: variables may change during the delay, altering the function's output. To preserve the original variable value, employ a callback function:
function callback(a) { return function() { alert("Hello" + a); } } var a = "world"; setTimeout(callback(a), 2000); a = "Stack Overflow"; // This change won't affect the delayed function
By embodying the original variable value within the callback function, it ensures that the delayed invocation occurs with the intended value, even if it has changed in the meantime.
The above is the detailed content of How to Execute Script After Specific Delay Using JavaScript and Prevent Variable Value Changes?. For more information, please follow other related articles on the PHP Chinese website!