Home > Web Front-end > JS Tutorial > How to Use setTimeout for Delayed JavaScript Execution?

How to Use setTimeout for Delayed JavaScript Execution?

Patricia Arquette
Release: 2024-11-01 03:32:28
Original
744 people have browsed it

How to Use setTimeout for Delayed JavaScript Execution?

Waiting for Script Execution with JavaScript

JavaScript provides a method called setTimeout that allows you to delay the execution of a script. Unlike jQuery's delay() or wait(), setTimeout works asynchronously.

Using setTimeout with a Function:

If you want to call a named function after a delay, you can use bracket notation:

<code class="js">setTimeout(functionName, delayInMilliseconds);</code>
Copy after login

Passing Parameters with an Anonymous Function:

However, if you need to pass parameters to the function, you must use an anonymous function enclosed in parentheses:

<code class="js">setTimeout(function() {
  alert("Hello " + parameter);
}, delayInMilliseconds);</code>
Copy after login

Dealing with Variable Changes:

Note that setTimeout uses the value of variables at the time the function is passed. To ensure the correct value is used, you can wrap the parameter in a callback function:

<code class="js">function callback(parameter) {
  return function() {
    alert("Hello " + parameter);
  }
}

let parameter = "world";
setTimeout(callback(parameter), delayInMilliseconds);</code>
Copy after login

The above is the detailed content of How to Use setTimeout for Delayed JavaScript Execution?. 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