Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
Why does setTimeout sometimes execute before a synchronous loop finishes in JavaScript?
Asked on Jan 01, 2026
Answer
In JavaScript, "setTimeout" is asynchronous and runs in the event loop, which allows it to execute after the current call stack is clear, even if a synchronous loop is still running. Here's a simple example to illustrate this behavior:
<!-- BEGIN COPY / PASTE -->
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
for (let i = 0; i < 1000000000; i++) {
// Simulating a long-running loop
}
console.log("End");
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "setTimeout" function schedules the "Timeout" message to be logged after 0 milliseconds, but it waits for the current call stack to finish.
- The "for" loop is synchronous and blocks the call stack until it completes.
- "Start" and "End" are logged before "Timeout" because the loop must finish before the event loop can process the "setTimeout" callback.
Recommended Links:
