This is the 16th day of my participation in Gwen Challenge
What is single threading?
The JS language is single-threaded and can only do one thing at a time.
Why is JavaScript single threaded?
The browser JS function is to manipulate the DOM, which determines that it can only be a single thread. Otherwise, there will be complex synchronization problems. For example, if JavaScript has two threads at the same time, one thread adds content to a DOM node, and the other thread removes the node, which thread should the browser use? Eventloop was created to coordinate events, user interactions, UI rendering, and network requests and prevent the main thread from blocking. Eventloop consists of two types: one is based on the Browsing Context and the other is based on Worker, both of which are independent. The main focus here is on browser-based event loops.
Task Queue
The event loop is implemented using the task queue mechanism. An Eventloop can have one or more task queues. A task queue is a set of ordered tasks.
There are two kinds of generalized tasks, one is synchronous task, the other is asynchronous task.
- All synchronization tasks are executed on the main thread, forming an execution stack;
- There’s another one out of the main thread
Task queue
, as long as the asynchronous task has the task running result, inTask queue
To place an event in; - Once the
Execution stack
After all synchronization tasks are completed, the system reads the dataTask queue
To see what events are there, and what asynchronous tasks are corresponding to them. Then the wait state ends, the stack starts, and the execution begins. - The main thread repeats step 3 above.
Synchronization task:
- The output
- Declaration of variables
- Synchronization function, etc.
Asynchronous tasks:
- SetTimeout and setInterval
- DOM events
- Promise
- ajax
- fileReader
- Asynchronous functions and so on
Macro and micro tasks
Macro task: Script (whole code) SetTimeout, setIntval, setImmediate, I/O, UI Interaction, Rending, postMessage, MessageChannel, requestAnimationFrame; Microtasks: Process. nextick, Promise, Object.observe, MutationObserver;
- When macro tasks enter the main thread, microtasks will be collected and added to the microtask queue during execution.
- After the execution of the macro task is completed, the tasks of the micro task will be executed immediately (successively). During the execution of the micro task queue, the macro task will be collected again and added to the macro task queue.
- Repeat step 1 and 2.
That is: macro task -> micro task -> Render and repeat
Note: Each round of the event loop performs one macro task and all microtasks; The task queue must be executed in first-in, first-out order.