Javascript execution order - execution order of functions in javascript

javascript execution order description.

Try to guess execution order of below code and compare it with output at the end of post. If its not matching this article will help you understand executioin order of javascript functions.

requestIdleCallback(()=>console.log(1));
setTimeout(()=>console.log(2));
Promise.resolve(3).then(console.log);
requestAnimationFrame(()=>console.log(4));
console.log(5);
window.onclick = ()=>console.log(6);
window.dispatchEvent(new Event('click'));

JavaScript is a single-threaded language

JavaScript is a single-threaded programming language. If we try to execute an infinite loop:

Infinite loop:

while(true) {

};

the browser will suggest killing the tab. Because that the tab thread is constantly busy executing loop and therefore is not able to refresh/rerender the browser window or do anything.

That is why should not add time consuming task to main event loop.

Execution priority

  1. Call stack: user code, click event, keyboard event, scroll event, etc
  2. Micro task queue: Micro task, such as Promise , Animation queue: requestAnimationFrame
  3. Macro task queue: macro tasks, such as setTimeout
  4. Idle queue: requestIdleCallback =>

Based on this priority we can classify each function

These are user code, click handler and click event so they will have highest priority

console.log(4);
window.onclick = ()=>console.log(5);
window.dispatchEvent(new Event('click'));

above code will be put in to the execute immediately after being in call stack. Its user synchronous code and event I/O

Now next priority is for Micro task

Promise.resolve(2).then(console.log);
requestAnimationFrame(()=>console.log(3));

Promise, requestAnimationFrame is consider to be Micro task and has next priority so it will be executed

Then Macro task queue

setTimeout(()=>console.log(1));

setTimeout macro task comes after Micor task queue so it will be executed next

Idle queue

requestIdleCallback(()=>console.log(1))

Last will be requestIdleCallback as name implies when all code is executed and call stack is empty then this code will be executed. think as if nothing to do execute this.

Execution out put

// output
5 // console.log user code
6 // event handling I/O
3 // Promise
4 // request animation frame
2 // set timeout
1 // requestIdleCallback

Now you know how javascript handles different functions in different way. This information will help you crack interview question as well make you better programer.

js interview questions