How Does setTimeout Work? Inside the Browser Event Loop Explained
setTimeout schedules code to run after a delay by handing the callback to the browser’s Web APIs, which later places it in the task queue; once the call stack is empty, the event loop processes the queued callback, illustrating the asynchronous execution flow in JavaScript.
JavaScript runs on a single thread, and setTimeout postpones execution of a callback while allowing the thread to continue processing other code.
The browser implements an event‑loop model: outside the JavaScript engine there is a task queue. When setTimeout is called, the timer is handed to the Web APIs; after the delay the timer pushes the callback onto the task queue. Once the call stack is empty, the engine pulls tasks from the queue in order and executes them.
Example code:
console.log('1');
setTimeout(function test(){
console.log('2');
}, 5000);
console.log('3');Execution steps illustrated:
log('1') is pushed onto the call stack and executed. setTimeout registers the test callback with the timer module (Web APIs).
log('3') is pushed onto the call stack and executed.
After 5 seconds the timer module detects that the delay has elapsed and adds the test callback to the task queue.
When the call stack becomes empty, the event loop dequeues the test callback, pushes it onto the stack, which then calls console.log('2'), producing the final output.
Images below illustrate each stage of the process:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
