Last Updated : 29 Nov, 2024
The setTimeout() function is used to add delay or scheduling the execution of a specific function after a certain period. It's a key feature of both browser environments and Node.js, enabling asynchronous behavior in code execution.
JavaScript
setTimeout(function() {
console.log('Hello, world!');
}, 2000);
Output
Hello, world!
Syntax
setTimeout(function, delay, arg1, arg2, ...);
Parameters
setTimeout() Function
JavaScript provides a corresponding function called clearTimeout()
to cancel a scheduled timeout before it gets executed.
function delayedFunction() {
console.log("This won't be executed due to clearTimeout");
}
let timeoutId = setTimeout(delayedFunction, 2000);
// Cancel the setTimeout before it executes
clearTimeout(timeoutId);
console.log("Timeout canceled");
2. Purpose of setTimeout()
Function
The setTimeout()
function is utilized to introduce a delay or to execute a particular function after a specified amount of time has passed. It is part of the Web APIs provided by browsers and Node.js, allowing asynchronous execution of code.
console.log("Start");
setTimeout(function() {
console.log("Delayed log after 2000 milliseconds");
}, 2000);
console.log("End");
Output
Start End Delayed log after 2000 milliseconds
Explanation
setTimeout()
function takes two parameters: a callback function and a time delay in milliseconds.setTimeout()
is set to execute the callback function (delayed log) after 2000 milliseconds (2 seconds).setTimeout()
.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4