ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Event Loop Simulation with Callbacks

JavaScript

Goal -- WPM

Ready
Exercise Algorithm Area
1function simulateEventLoop() {
2console.log("Script start");
3
4setTimeout(() => {
5console.log("setTimeout 1 (macrotask)");
6Promise.resolve().then(() => console.log("setTimeout 1 inner promise (microtask)"));
7}, 0);
8
9setTimeout(() => {
10console.log("setTimeout 2 (macrotask)");
11}, 0);
12
13Promise.resolve().then(() => {
14console.log("Promise 1 (microtask)");
15setTimeout(() => console.log("Promise 1 inner setTimeout (macrotask)"), 0);
16});
17
18Promise.resolve().then(() => {
19console.log("Promise 2 (microtask)");
20});
21
22console.log("Script end");
23}
24
25simulateEventLoop();
Algorithm description viewbox

Event Loop Simulation with Callbacks

Algorithm description:

This algorithm models the behavior of the JavaScript event loop, illustrating the execution order of synchronous code, macrotasks (like `setTimeout`), and microtasks (like `Promise.then`). Understanding this order is fundamental to predicting and controlling the flow of asynchronous operations in JavaScript, which is vital for writing predictable and efficient code.

Algorithm explanation:

The JavaScript event loop processes tasks in a specific order. Synchronous code at the top level executes first. Then, the event loop checks the microtask queue. Any promises that resolve and have `.then()` callbacks attached are added to this queue. Microtasks are executed after the current script finishes and before the event loop moves to the next macrotask. Macrotasks, such as those scheduled by `setTimeout` or `setInterval`, are placed in a separate queue. The event loop picks one macrotask at a time, executes it, and then processes all microtasks that may have been added during its execution, before picking the next macrotask. This simulation demonstrates how `setTimeout(..., 0)` is treated as a macrotask, while `Promise.resolve().then(...)` creates microtasks, showing their relative priorities.

Pseudocode:

log "Script start"

schedule setTimeout 1 with callback: log "setTimeout 1 (macrotask)", then schedule inner promise: log "setTimeout 1 inner promise (microtask)"

schedule setTimeout 2 with callback: log "setTimeout 2 (macrotask)"

schedule Promise 1 with callback: log "Promise 1 (microtask)", then schedule inner setTimeout: log "Promise 1 inner setTimeout (macrotask)"

schedule Promise 2 with callback: log "Promise 2 (microtask)"

log "Script end"

// Event loop processing:
// 1. Execute synchronous code.
// 2. Execute all microtasks.
// 3. Execute one macrotask.
// 4. Execute all microtasks.
// 5. Repeat steps 3-4 until all tasks are done.