JavaScript setTimeout: Timers & Event Loop Guide
Direct Answer & Overview
The JavaScript setTimeout() function schedules a callback function to execute after a minimum delay in milliseconds. Because JavaScript runs on a single-threaded event loop, setTimeout places callbacks in the task queue after the main thread clears.
JavaScript Source Code
console.log("Start");
setTimeout(() => {
console.log("Delayed output");
}, 1000);
console.log("End");How does this JavaScript code work?
The `setTimeout()` method is part of the Web APIs and Node.js timers module. It accepts a callback function and a delay in milliseconds. Crucially, the delay represents the *minimum* time before the task is placed onto the macrotask queue. The callback will not execute until the call stack is completely clear of all synchronous code, demonstrating the non-blocking asynchronous event loop mechanism of JavaScript.
What is the expected terminal output?
Executing this code in JS CodeLab produces the following stdout sequence in the developer console:
Start
End
Delayed outputCommon mistakes to avoid
- !Passing an immediate function invocation like setTimeout(fn(), 1000) instead of a function reference setTimeout(fn, 1000).
- !Assuming setTimeout guarantees exact execution timing; heavy synchronous computation can delay timer execution indefinitely.
- !Passing string code to setTimeout, which invokes dangerous eval-like compilation.
- !Forgetting to clear active intervals or timeouts with clearTimeout(timerId) on component unmount, causing memory leaks.
Frequently Asked Questions
Does setTimeout(fn, 0) execute immediately?
No. A delay of 0ms defers execution until the current synchronous execution stack has finished and microtasks have drained.
How do you cancel a scheduled setTimeout timer?
Store the integer timer ID returned by setTimeout, and pass it to clearTimeout(timerId) before the timer fires.
Why does console.log('End') print before setTimeout in this example?
Synchronous code runs immediately on the call stack, while timer callbacks are dispatched to the browser task queue and run only after the stack is clear.
Comprehensive Tutorial
Want an in-depth understanding of this topic?
Read our complete, interactive tutorial covering memory management, edge cases, and best practices.
Read the full promises tutorial →