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

How to Use setTimeout for Delayed JavaScript Execution?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 03:32:28771browse

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>

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>

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>

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!

Statement:
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