This is the third day of my participation in the August Text Challenge.More challenges in August
To understand some concepts:
JS
There are synchronous tasks and asynchronous tasks- Synchronization tasks are executed on the JS engine thread, forming an execution stack
- The event trigger thread manages a task queue, and the asynchronous task trigger condition is reached, putting the callback event into the task queue
- When all synchronous tasks in the execution stack are completed and the JS engine thread is idle, the system reads the task queue and adds the asynchronous task callback event that can be run to the execution stack to start the execution
- In front end development we will pass
setTimeout/setInterval
To specify a scheduled taskXHR/fetch
Sending network Requests - So let me give you a brief overview
setTimeout/setInterval
andXHR/fetch
What did he do - We know, whether it’s
setTimeout/setInterval
andXHR/fetch
The code, as it executes, is itself a synchronous task, and its callbacks are asynchronous tasks - When the code executes to
setTimeout/setInterval
When the JS engine thread notifies the timer trigger thread, after an interval, a callback event will be triggered - The timer trigger thread receives the message and, after waiting for the time, places the callback event into the event queue managed by the event trigger thread
- When the code executes to
XHR/fetch
In fact, it isJS
Engine thread notifications are asynchronoushttp
The request thread, which sends a network request and sets a callback event when the request completes - The asynchronous
http
Upon receiving the message, the requesting thread, upon success of the request, places the callback event into the event queue managed by the thread that triggered the event - When our synchronization task is complete,
JS
The engine thread will ask the event-triggering thread if there are any callback functions waiting to be executed in the event queue, and if there are any, it will be added to the execution stack for the JS engine thread to execute
To sum up:
- The JS engine thread only executes the events in the execution stack
- When the code in the execution stack completes, it reads the events in the event queue
- Callback events in the event queue are inserted into the event queue by the respective thread
- The cycle
Now that we have a basic understanding of what an execution stack is and what an event queue is, let’s take a closer look at macro and micro tasks in an event loop