JS operation mechanism

Time:2021-7-22

Single thread: JS is single thread. JS can only do one thing at a time. This is called single thread

Task queue: asynchronous process and single thread itself seem to conflict. It is task queue that makes the two not conflict

Note: synchronous task is prior to asynchronous task

Synchronization task: the task running synchronously in JS is called synchronization task

Asynchronous tasks: setTimeout and setinterval, DOM events, and promise in ES6 are called asynchronous tasks

 

Event loop

  1. The runtime stack runs the synchronization task
  2. The browser recognizes that the event is an asynchronous task, and it does not put it on the runtime stack, but takes it away. After taking it away, it is not immediately put into the asynchronous queue. After the synchronous task is executed, it is put into the asynchronous queue (the minimum time of setTimeout is 10ms in the previous browser and 4ms in the latest browser. If it is set to 0 or < 4ms, it is regarded as 4ms) (when do I go to the asynchronous queue to get this task?)
  3. When the runtime stack has no tasks, it starts to execute asynchronous tasks (at this time, asynchronous tasks become synchronous tasks). After execution, if there is no task in the running stack, listen to the asynchronous task again. The loop process is event loop (when to put asynchronous tasks in the task queue)

When to start asynchronous tasks

  • SetTimeout and setinterval
  • DOM events
  • Promise in ES6