Event_Loop_Js
Event_Loop_Js
To make this clear, I’ll break down the execution priorities of various operations in JavaScript, including
functions, promises, loops, variables, objects, async/await, setTimeout, and other elements in the
event loop cycle.
· Highest priority: Synchronous code executes immediately, as part of the call stack. It does not
go into any queue.
· Normal Functions: Regular function calls are executed in the current execution context.
· Loops: Loops (like for, while) are part of the synchronous code and execute immediately as
well.
· Variables: Variable assignments and declarations (like let, const, var) are part of the
synchronous execution.
· Higher priority than callback queue: After synchronous code execution, the event loop checks
the microtask queue.
· Promises: The .then(), .catch(), and .finally() handlers for promises are added to the microtask
queue. They run after synchronous code, but before any tasks in the callback queue.
· queueMicrotask(): Tasks added with queueMicrotask() are placed in the microtask queue and
executed before the callback queue.
· Async/Await: async/await works with promises. When an await is encountered, it pauses the
execution of the async function until the promise resolves. The code after await is added to
the microtask queue and will be executed after the current synchronous code, but before
callback queue tasks.
· Event Listeners: Event handler callbacks (e.g., click, keydown, etc.) are placed in the callback
queue and processed in the order they are added.
· I/O callbacks: Any other I/O operations, such as reading files or network requests, add their
callbacks to the callback queue.
D]
D]Rendering/Other Tasks:
· Lowest priority: After processing the callback queue, the browser (or environment) may
perform repainting, reflowing, or other rendering tasks.
· These are typically not something developers control directly, but they occur after all
JavaScript execution is completed.
console.log('Start');
setTimeout(() => {
console.log('setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('Promise 1');
});
console.log('Async Start');
await Promise.resolve();
console.log('Async End');
asyncFunction();
setTimeout(() => {
console.log('setTimeout 2');
}, 0);
console.log('End');
Execution Order:
'Start' (synchronous log)
Microtasks:
Microtasks (continued):
Callback Queue: