Home > Web Front-end > JS Tutorial > body text

How to Execute Script After Specific Delay Using JavaScript and Prevent Variable Value Changes?

Susan Sarandon
Release: 2024-10-31 22:38:02
Original
642 people have browsed it

How to Execute Script After Specific Delay Using JavaScript and Prevent Variable Value Changes?

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!