亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Web Front-end JS Tutorial setTimeout JavaScript Function: Guide with Examples

setTimeout JavaScript Function: Guide with Examples

Feb 10, 2025 pm 02:34 PM

setTimeout JavaScript Function: Guide with Examples

JavaScript's setTimeout Function explanation: Implement delayed execution

setTimeout is a native function in JavaScript that is used to call functions or execute code snippets after a specified delay (milliseconds). This is useful in many scenarios, such as displaying a pop-up window after the user browses the page for a while, or adding a brief delay before removing the element hover effect (preventing misoperation).

Key points:

  • JavaScript's setTimeout function allows the execution of functions or code snippets after a specified number of milliseconds, which is very useful for tasks such as displaying popups after a certain browsing time.
  • setTimeout Accepts a function reference as the first parameter, which can be a function name, a variable that references the function, or anonymous function. It can also execute code strings, but it is not recommended as this will reduce readability, security and speed.
  • You can use an anonymous function as the first parameter to pass the parameter to the callback function executed by setTimeout. However, an alternative to listing parameters after delay is incompatible with IE9 and below.
  • In the code executed by setTimeout, the value of this runs in a different execution context than the function that calls it, which can cause problems when the context of the this keyword is important. This can be solved using bind, library functions, or arrow functions.
  • The return value of
  • setTimeout is a numeric ID that can be used to cancel the timer in conjunction with the clearTimeout function.

setTimeout Example of use

The following code block shows a simple example that prints the message to the console after a timeout of 2 seconds (2000 milliseconds):

function greet() {
  console.log('Howdy!');
}
setTimeout(greet, 2000);

To demonstrate this concept in more detail, the following demonstration displays a pop-up window after clicking the button two seconds: (Please visit CodePen to view the demo)

Grammar

According to the MDN documentation, the syntax of setTimeout is as follows:

const timeoutID = setTimeout(code);
const timeoutID = setTimeout(code, delay);

const timeoutID = setTimeout(functionRef);
const timeoutID = setTimeout(functionRef, delay);
const timeoutID = setTimeout(functionRef, delay[, arg1, arg2, /* … ,*/ argN])

Of:

  • timeoutID is a digital ID that can be used in conjunction with clearTimeout to cancel the timer.
  • scope refers to the Window interface or the WorkerGlobalScope interface.
  • functionRef is the function to be executed after the timer expires.
  • code is an alternative syntax that allows you to include strings instead of functions that are compiled and executed when the timer expires.
  • delay is the number of milliseconds that a function call should be delayed. If omitted, the default is 0.
  • arg1, ..., argN are other parameters passed to the function specified by functionRef.

Note: Square brackets [] indicate optional parameters.

setTimeout and window.setTimeout

You will notice that sometimes the syntax contains window.setTimeout. Why is this?

When running code in a browser, scope will refer to the global window object. setTimeout and window.setTimeout refer to the same function, the only difference is that in the second statement, we refer to the setTimeout method as the property of the window object.

In my opinion, this adds complexity, while the benefits are minimal. If you define another setTimeout method that will be found first and returned in the scope chain, then you may have bigger issues to worry about.

In this tutorial, I will omit window, but in the end, it's up to you which syntax you choose.

setTimeout Example of usage of method

setTimeout The method accepts a function reference as the first parameter.

This can be the name of the function:

function greet() {
  console.log('Howdy!');
}
setTimeout(greet, 2000);

Variables that reference functions (function expression):

const timeoutID = setTimeout(code);
const timeoutID = setTimeout(code, delay);

const timeoutID = setTimeout(functionRef);
const timeoutID = setTimeout(functionRef, delay);
const timeoutID = setTimeout(functionRef, delay[, arg1, arg2, /* … ,*/ argN])

Or anonymous function:

function greet() {
  alert('Howdy!');
}
setTimeout(greet, 2000);

As mentioned above, you can also pass the code string to setTimeout for its execution:

const greet = function() {
  alert('Howdy!');
};
setTimeout(greet, 2000);

However, this is not recommended for the following reasons:

  • Hard to read (and therefore difficult to maintain and/or debug).
  • It uses implicit eval, which is a potential security risk.
  • It's slower than the alternative because it has to call the JS interpreter.

Passing parameters to setTimeout

In the basic scenario, the preferred cross-browser method is to pass the argument to the callback function executed by setTimeout using an anonymous function as the first parameter.

In the following example, we select a random animal from the animals array and pass this random animal as a parameter to the makeTalk function. Then, setTimeout executes the makeTalk function with a delay of one second:

setTimeout(() => { alert('Howdy!'); }, 2000);

Note: I used a regular function (getRandom) to return a random element from the array. You can also write it as a function expression using arrow functions:

setTimeout('alert("Howdy!");', 2000);

We will introduce the arrow function in the next section. Here is a CodePen containing the above code (you need to open the console to view the output).

Alternative Method

From the syntax at the top of the article, it can be seen that there is a second method to pass parameters to the callback function executed by setTimeout. This involves listing any parameters after the delay.

Refer to our previous example, this will give us:

function makeTalk(animal) {
  const noises = {
    cat: 'purr',
    dog: 'woof',
    cow: 'moo',
    pig: 'oink',
  }

  console.log(`A ${animal} goes ${noises[animal]}.`);
}

function getRandom(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

const animals = ['cat', 'dog', 'cow', 'pig'];
const randomAnimal = getRandom(animals);

setTimeout(() => {
  makeTalk(randomAnimal);
}, 1000);

Unfortunately, this does not work in IE9 or below, where the parameters are passed as undefined. If you unfortunately need support for IE9, a polyfill is provided on MDN.

this Keyword Questions

setTimeout Executed code runs in a different execution context than the function that calls it. This becomes a problem when the context of the this keyword is important:

function greet() {
  console.log('Howdy!');
}
setTimeout(greet, 2000);
The reason for this output is that in the first example,

points to the this object, and in the second example, dog points to the global this object (it does not have the window attribute) . sound

To solve this problem, there are various ways...

Explanatory setting of the value of

this

You can use the

method to create a new function, and when called, its bind keyword will be set to the provided value (in this case the bind object) . This will give us: this dog

User library
const timeoutID = setTimeout(code);
const timeoutID = setTimeout(code, delay);

const timeoutID = setTimeout(functionRef);
const timeoutID = setTimeout(functionRef, delay);
const timeoutID = setTimeout(functionRef, delay[, arg1, arg2, /* … ,*/ argN])

Many libraries come with built-in functions to solve this problem. For example, the

method of jQuery. It accepts a function and returns a new function that will always have a specific context. In this case, that would be:

jQuery.proxy()

Use arrow function in
function greet() {
  alert('Howdy!');
}
setTimeout(greet, 2000);

The arrow function was introduced in ES6. They are much shorter than the syntax of regular functions: setTimeout

Of course, you can use them with

, but one thing to note - the arrow function does not have its own
const greet = function() {
  alert('Howdy!');
};
setTimeout(greet, 2000);
value. Instead, they use the

value of the enclosed lexical context. setTimeout thisUse regular function: this

Use the arrow function:

setTimeout(() => { alert('Howdy!'); }, 2000);

In the second example,

points to the global
setTimeout('alert("Howdy!");', 2000);
object (again, it does not have a

property). this window This can get us into trouble when using the arrow function with sound. We have seen before how to provide the correct

value for the function called in

: setTimeout setTimeout this This will not work when using the arrow function in the introduced method, because the arrow function does not have its own

value. This method will still record
function makeTalk(animal) {
  const noises = {
    cat: 'purr',
    dog: 'woof',
    cow: 'moo',
    pig: 'oink',
  }

  console.log(`A ${animal} goes ${noises[animal]}.`);
}

function getRandom(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

const animals = ['cat', 'dog', 'cow', 'pig'];
const randomAnimal = getRandom(animals);

setTimeout(() => {
  makeTalk(randomAnimal);
}, 1000);
.

thisWriting cleaner code using arrow functions and undefined

However, because the arrow function does not have its own

value, it can also give us an advantage. setTimeout

Consider code like this:

this

It can be rewrited more concisely using the arrow function:

const getRandom = arr => arr[Math.floor(Math.random() * arr.length)];
If you want to know the beginning of arrow functions, read "ES6 Arrow Functions: Concise Syntax in JavaScript".

Cancel timer
setTimeout(makeTalk, 1000, randomAnimal);

As we learned at the beginning of the article, the return value of

is a numeric ID that can be used in conjunction with the

function to cancel the timer:

function greet() {
  console.log('Howdy!');
}
setTimeout(greet, 2000);

Let's see how it actually works. In the Pen below, if you click the Start Countdown button, the countdown will begin. If the countdown is completed, the kitten wins. However, if you press the "Stop Countdown" button, the timer will be stopped and reset. (If you don't see a cool effect when the countdown reaches zero, rerun Pen using the button embedded on the right side of the bottom.)

Summary

In this article, I demonstrate how to use setTimeout to delay the execution of a function. I also showed how to pass parameters to setTimeout, how to maintain the this value inside its callback function, and how to cancel the timer.

setTimeout FAQs for JavaScript Functions

  • setTimeout What is in JavaScript?

    setTimeout is a built-in function in JavaScript that allows you to schedule the execution of a function or code segment after a specified delay (in milliseconds).

  • setTimeout How does it work?

    When you call the setTimeout function, you need to provide two parameters: the function or code to execute, and the delay in milliseconds. The provided functions/code will be added to the queue and after the specified delay, it will be moved from the queue to the call stack for execution.

  • What are the alternatives to using setTimeout?

    Yes, there are alternatives, such as setInterval, which will repeat the function at specified intervals, and the newer requestAnimationFrame, which is for smoother animations and better browser performance.

  • When shouldn't be used setTimeout?

    setTimeout is a useful tool for scheduling asynchronous code execution in JavaScript, but in some cases it may not be the best choice. For precise animations or games, you should use requestAnimationFrame. You should not nest multiple setTimeout calls; it is better to use Promise or asynchronous mode. setTimeout Inaccurate for delays less than 10 milliseconds; consider alternatives. If you are building a real-time application (such as online multiplayer games or financial trading platforms), choose real-time technologies such as WebSockets. Large CPU-intensive tasks can block event loops; use Web Workers if needed.

  • Can I cancel the setTimeout operation?

    Yes, you can use the clearTimeout function to cancel the scheduled timeout. It takes the timeout ID returned by setTimeout as a parameter. For example: const timeoutId = setTimeout(myFunction, 1000); clearTimeout(timeoutId);

  • What is the difference between

    setTimeout and setInterval?

    setTimeout Schedule the function to run once after the specified delay, while setInterval Schedule the function to run repeatedly at the specified interval until it is cancelled or the program stops.

  • What is the minimum delay value that I can use setTimeout?

    The minimum delay value is 0, which means that the function is scheduled to be executed before the current thread completes but handles any pending events. However, the actual granularity of the timer varies from browser to browser and environment to different browsers. Some environments may not support delays of less than 10 milliseconds.

  • setTimeout What is in Node.js?

    setTimeout is a built-in function for Node.js that delays the execution of a given function or code block by specified number of milliseconds.

  • How to use setTimeout in Node.js?

    You can use the setTimeout function as follows: setTimeout(callback, delay); where callback is the function you want to execute after the specified millisecond delay.

  • What are the best practices for using setTimeout in Node.js?

    Some best practices include using named functions as callbacks, handling errors gracefully, and understanding the behavior of event loops to avoid unexpected delays or blockages. Also, consider using setImmediate to execute immediately during the next event loop cycle.

(Note that because the input text contains a link to CodePen, I cannot render the content of CodePen directly in the output. You need to visit the link provided in the article to view the CodePen demo.)

The above is the detailed content of setTimeout JavaScript Function: Guide with Examples. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. Jul 08, 2025 pm 02:27 PM

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

React vs Angular vs Vue: which js framework is best? React vs Angular vs Vue: which js framework is best? Jul 05, 2025 am 02:24 AM

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Jul 04, 2025 am 02:42 AM

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

What is the cache API and how is it used with Service Workers? What is the cache API and how is it used with Service Workers? Jul 08, 2025 am 02:43 AM

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Jul 08, 2025 am 02:40 AM

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

See all articles