DEV Community

tanjiagang
tanjiagang

Posted on

Detailed explanation of Javascript event loop rules

As is well known, Javacript is a single thread language, but why can we use asynchronous operation? Because asynchronous operations are executed by a browser with multi-thread and multi-process capabilities. Javascript always runs on a single thread throughout and is handed over to the browser for execution when asynchronous code is decovered, the browser then call the corresponding thread or process, including http request, GUI, event triggering, etc., to handle these async opertions.

Generally speaking, Javasctip tasks can be divided into three categories: sync task, micro task, and macro task, running in the order of sync -> micro -> macro. The sync code is executed first then the browser will put micro code into a micro task queue wating for sync task to complete, and put macro code into a macro task queue wating for micro code to complete.
This priority order is similar to mutil-level feedback queue scheduling algorithm on OS.

common micro task: Promise.then(), Promise.catch(), new MutationObserver(), process.nextTick()
common macro task: setTimeout, setInterview, requestAnimationFrame()

By the way, process.nextTick() is neither micro task nor macro task and it simply runs after sync code and before micro task.

Top comments (0)