setTimeout
and setInterval
in JavaScriptsetTimeout
and setInterval
?setTimeout and setInterval are built-in Web API methods provided by browsers to schedule tasks:
setTimeout(function, delay)
→ Runs the function once after the delay (in ms).setInterval(function, delay)
→ Runs the function repeatedly every delay milliseconds.clearTimeout()
and clearInterval()
stop scheduled functions.JavaScript is single-threaded and uses an Event Loop to handle asynchronous tasks like timers.
setTimeout
, it sends it to...
The Event Loop constantly checks the stack. When it's empty, it pushes the next callback from the queue to the stack for execution.
The GIF below shows how Call Stack → Web APIs → Callback Queue work together.
function greet() {
console.log("Hello from setTimeout!");
}
setTimeout(greet, 2000);
setTimeout(() => {
console.log("Executed after 3 seconds.");
}, 3000);
const intervalId = setInterval(() => {
console.log("Repeating every 5 seconds.");
}, 5000);
clearTimeout(timerId); // Cancels a timeout
clearInterval(intervalId); // Cancels a repeating interval
console.log("Start");
setTimeout(() => {
console.log("Inside setTimeout");
}, 0);
console.log("End");
// Output:
// Start
// End
// Inside setTimeout