Concept : Execute tasks and collect asynchronous tasks. When the call stack is idle, an execution mechanism that repeatedly calls the callback function in the task queue
Reason : JavaScript is single-threaded. In order not to block the JS engine, design a model for executing code
How to execute the code in JS :
Execute synchronous code, and hand it over to the host browser environment for execution when encountering asynchronous code. After the asynchronous result is obtained, the callback function is queued in the task queue. When the call stack is free, the callback function in the task queue is called repeatedly
case :
console.log(1)
setTimeout(() => {
console.log(2)
}, 0)
console.log(3)
setTimeout(() => {
console.log(4)
}, 2000)
console.log(5)
Implementation process:
1-JS engine puts it console.log(1)
into the call stack and pops it up after execution
2-JS engine finds that setTimeout(…, 0)
it is an asynchronous code, so it puts it into the host environment (browser), executes it setTimeout(…, 0)
, and puts it into the task queue after completion
3-JS engine puts it console.log(3)
into the call stack and pops it up after execution
4-JS engine finds that setTimeout(…, 2000)
is an asynchronous code, so it puts it into the host environment (browser), waits for setTimeout(…, 2000)
2s for execution, and puts it into the task queue after completion
5-JS engine puts it console.log(5)
into the call stack and pops it up after execution
setTimeout(…, 0)
6- At this point, the call stack of JS is idle, and the callback function in the task queue is called. The callback function in the task queue is called first console.log(2)
, and then popped out of the stack after execution. At this point, the call stack of JS is free again, and it will keep monitoring the task queue. When 2s arrives, setTimeout(…, 2000)
the callback function in will be called console.log(4)
, and the stack will be popped after execution.
Reference: AJAX-Day04-07. Event Loop_哔哩哔哩_bilibili