setTimeout
is a method in JavaScript that allows you to execute a function or code snippet after a specified delay in milliseconds. It does not block the execution of the main code thread; instead, it registers a timer and continues execution. It is a primary tool for creating asynchronous operations, such as delayed notifications, animations, or performing tasks without freezing the user interface. To cancel a timer, clearTimeout
is used.
setTimeout
is a built-in function in browsers and Node.js that allows you to schedule the execution of a function after a certain amount of time. It returns a numeric timer ID that can be used to cancel it.
const timerId = setTimeout(callback, delay, ...args);
callback
: The function to be executed.delay
: The delay in milliseconds (1000 ms = 1 second). If not specified, it defaults to 0....args
: Additional arguments that will be passed to the callback
when it is called.setTimeout
does not guarantee that the function will execute exactly after the specified time. It guarantees that it will be added to the callback queue no earlier than after the delay
.
setTimeout
passes the timer to the Web APIs.callback
is placed in the callback queue.callback
from the queue is moved to the stack and executed.This is why setTimeout(fn, 0)
does not execute immediately but is placed at the end of the queue, yielding to the current code.
console.log("Hello!");
setTimeout(() => {
console.log("This code will run after 2 seconds.");
}, 2000);
console.log("This code will not wait.");
Console output:
function greet(name, phrase) {
console.log(`${phrase}, ${name}!`);
}
setTimeout(greet, 1500, "Alexander", "Good day");
// Outputs: "Good day, Alexander!" after 1.5 seconds
clearTimeout
If you want to cancel a scheduled execution, use clearTimeout
, passing it the timerId
.
const timerId = setTimeout(() => {
console.log("This message will never appear.");
}, 5000);
console.log(`Timer with ID ${timerId} has started.`);
// Cancel the timer after 2 seconds
setTimeout(() => {
clearTimeout(timerId);
console.log(`Timer with ID ${timerId} has been canceled.`);
}, 2000);
// In what order will the numbers appear in the console?
console.log(1);
setTimeout(() => console.log(2), 1000);
setTimeout(() => console.log(3), 0);
console.log(4);
Explanation:
console.log(1)
is executed synchronously.setTimeout
with a 1000 ms delay registers a timer.setTimeout
with a 0 ms delay places console.log(3)
in the callback queue.console.log(4)
is executed synchronously.console.log(3)
.console.log(2)
is executed.// Write a function that logs numbers from 1 to 5
// to the console with a 1-second interval between each number.
function printNumbers() {
// Your code
}
printNumbers();
function printNumbers() {
for (let i = 1; i <= 5; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
}
Explanation: We use let
to create a block scope for i
. Each loop iteration creates a new i
variable, which setTimeout
“remembers”. The delay i * 1000
ensures that the numbers are logged sequentially every second.