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

setTimeout JavaScript Function: Guide with Examples

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-02-10 14:34:10
Original
781 people have browsed it

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

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

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

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

Or anonymous function:

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

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

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

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

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

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

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);
Copy after login
Copy after login
Copy after login
Copy after login
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])
Copy after login
Copy after login
Copy after login

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

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);
Copy after login
Copy after login
value. Instead, they use the

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

Use the arrow function:

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

In the second example,

points to the global
setTimeout('alert("Howdy!");', 2000);
Copy after login
Copy after login
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);
Copy after login
Copy after login
.

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)];
Copy after login
If you want to know the beginning of arrow functions, read "ES6 Arrow Functions: Concise Syntax in JavaScript".

Cancel timer
setTimeout(makeTalk, 1000, randomAnimal);
Copy after login

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

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template