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 ofthis
runs in a different execution context than the function that calls it, which can cause problems when the context of thethis
keyword is important. This can be solved usingbind
, 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 theclearTimeout
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 withclearTimeout
to cancel the timer.scope
refers to theWindow
interface or theWorkerGlobalScope
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 byfunctionRef
.
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);
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
Explanatory setting of the value of
this
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
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()
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 ownconst greet = function() { alert('Howdy!'); }; setTimeout(greet, 2000);
value of the enclosed lexical context. setTimeout
this
Use regular function: this
Use the arrow function:
setTimeout(() => { alert('Howdy!'); }, 2000);
In the second example,
points to the globalsetTimeout('alert("Howdy!");', 2000);
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
: 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
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);
this
Writing cleaner code using arrow functions and undefined
value, it can also give us an advantage. setTimeout
this
const getRandom = arr => arr[Math.floor(Math.random() * arr.length)];
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 thefunction 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 newerrequestAnimationFrame
, 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 userequestAnimationFrame
. You should not nest multiplesetTimeout
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 bysetTimeout
as a parameter. For example:const timeoutId = setTimeout(myFunction, 1000); clearTimeout(timeoutId);
-
What is the difference between
setTimeout
andsetInterval
?setTimeout
Schedule the function to run once after the specified delay, whilesetInterval
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);
wherecallback
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.
