event loop event polling mechanism

1, event loop (event polling/event loop)

首先我们要知道 由于js是单线程的脚本,异步事件要基于回调来实现的
而event loop 就是异步回调的实现原理

1. The execution order of js

  1. From front to back, execute line by line
  2. If an error is reported when a line is executed, the execution of the following code will be stopped
  3. Execute synchronous code first, then execute asynchronous

For example,
Small case
the above is a small case of js execution order

Browser running
The above is the browser operation.

First run the first line of code, display console.log('Hi'), and then clear the air conditioning stack.

Insert picture description here
Then call the function, the function will enter the asynchronous function queue and
Insert picture description here
finally execute the log code, and then clear it.
Insert picture description here
Then there is no synchronous code, the event loop mechanism will be started, and the browser will trigger the callback
Insert picture description here
Insert picture description here
to finish the execution.

同步代码,一行一行放在call stack 中执行
遇到异步,会先“记录”下,等待时机(定时、网络请求等)
时机到了,就会移动到callback Queue 库里面
如call stack 为空(即同步代码执行完)event loop 开始工作
轮训查找 callback Queue,如果有就移动到 call stack执行
然后继续轮训查找(和永动机一样)

Refer to the documentation for an
in-depth understanding of Javascript's Callstack&EventLoop
browser operating mechanism.

2. Macro task, micro task

js single thread-event execution sequence, macro task and micro task

Guess you like

Origin blog.csdn.net/weixin_53687450/article/details/115056994