JavaScript synchronization, asynchronousness and event loop

1. What is synchronous and asynchronous?

    1. Synchronization: It can be understood as having your own order for doing things (or as a list of completed things). Only when you have done this thing can you do the next thing. Just like walking, you can only move with your left foot. right foot

    2. Asynchronous: Contrary to the above, you don’t follow the order of the list. You can go back to the previous thing after completing it or even halfway through it.

2. Synchronization and asynchronousness of JS

     1. JS is a single-threaded language and can only do one thing at the same time; because DOM rendering, network requests, etc. are time-consuming, synchronization will block code execution and requires asynchronous execution. JS asynchronous tasks are executed in the form of callbacks.

     2. In JS, always execute the synchronous code first, and then execute the asynchronous code.

3. What is an event loop?

    1. The event loop is actually the execution mechanism of js synchronous and asynchronous code:                

       1) Execute line by line from front to back

       2) If an error is reported when executing a certain line, stop the execution of the following code

       3) First execute the synchronous code, and then execute the asynchronous code

     2.The specific execution process of event loop

        1) Synchronous code, executed line by line

        2) When encountering asynchronous, it will be recorded first and wait for the opportunity (timing, network request, etc.)

        3) When the time comes, move to the callback queue

        4) If the call stack is empty (that is, the synchronization code is executed) the event loop starts to work

        5) Poll to find the callback queue, if there is one, move to the call stack for execution

        6) Then continue polling to find

4. Macro tasks and micro tasks

    1. JS asynchronous code is divided into macro tasks and micro tasks

    2. Macro tasks: setTimeout, setInterval, Ajax, DOM events, etc.

       Microtask: Promise async/a

Guess you like

Origin blog.csdn.net/qq_45199056/article/details/126259262