Article content output source: pull hook education front-end high salary training camp

Knowledge:

  1. Asynchronous JS implementation
  2. EventLoop, message queue
  3. Macro and micro tasks

Synchronous mode and asynchronous mode

The first step is to make sure that JS is a single-threaded language, and that JS was originally designed for user interaction and manipulation of the DOM. This determines that it can only be single-threaded (for example, multi-threading the same DOM, one deletion at a time, one modification at a time, which can cause conflicts). However, in synchronous mode only, the page will block in the event of time-consuming operations, such as the interface does not request data, or the image is not finished loading, the page will be stuck waiting. This is obviously not practical or practical. So asynchronous mode came into being. You may be wondering how single-threaded JS can perform asynchronous operations. It is understood that javascript is a single-threaded language, but the runtime environment can be multithreaded (e.g. Browser, Node..). . The Worker class launched after JS is also implemented in this way.

Let’s do a warm-up test to see if your answer matches the console scoreIf your answer is not correct, I will help you analyze the order in which the JS code runs

  1. Run the main thread first. The console.log synchronization code is pushed directly onto the execution stack, executed and displayed, and global Begin is printed on the page
  2. When we encounter the setTImeout asynchronous code, the function goes to the Event Table and registers the function. WebAPIs help us count down the time. When the count down is over, we put the callback function into the Event Queue and wait for the main thread to finish running. Tasks in the queue are automatically put into the main thread to continue executing
  3. Timer1 and Timer2 are queued after the countdown, and the main thread continues to execute. Global End is printed
  4. Since timer2 has a short countdown, it was put into the queue early, so print Timer2 Invoke and then register inner to start the countdown. After that, print Timer1 Invoke.
  5. Finally, fetch the event from the queue and print the Inner Invoke

How, learn to waste ~~ read this you should have a preliminary understanding of synchronous asynchrony

A common development trick: setTimeout(fn,0), code is queued and waits for the main thread to complete before executing. In fact, there is no 0 rule for lifting a mouth. The minimum processing is 4ms


There’s a big hole here, like setTimeout set 3000, 3 seconds delay, but it’s usually not strictly 3 seconds, 4s? 5 s? The reason for this is that the callback function is queued after 3s, waiting for the main thread to complete. The execution time of the main thread is unknown, you can block all the time…


EventLoop

The so-called event loop is a three-step continuous loop of JS execution

  1. Synchronous main thread
  2. The asynchronous function is registered in the eventTable and placed in the eventQueue when it is finished
  3. Synchronize main thread completes, fetch eventQueue to main thread

Macro Tasks vs. Microtasks

Both tasks are asynchronous, and the difference is the order in which they are executed. I conclude a word, message queue has micro first micro, micro pluggable macro queue.

  • Macro tasks: Script (main thread), setTimeout, setInterval, setImmediate
  • Microtasks: Promise’s then (the execution function passed in by the Promise will immediately execute and belong to synchronization), process.nextTick (node environment), Object.observe(deprecated), MutationObserver (observing DOM changes)

Let me give you a problem to make sense of

Promise.resolve().then(()=>{ console.log('Promise1') setTimeout(()=>{ console.log('setTimeout2') },0) }) Resolve (). Then (()=>{console.log(' promise. log ')})},0) // Promise1, SetTimeout1, Promise2, setTimeout2Copy the code

What is the meaning of the passage?

  1. Then functions belong to asynchronous microtasks. SetTimeout1 belongs to asynchronous macro tasks. After 0 delay, all functions are put into the event loop
  2. When the main thread is finished, put the function in the event ring into the main thread, micro then macro, print Promise1, and then setTimeout is encountered again, put into the event ring.
  3. The setTimeout1 callback executes, prints setTimeout1, meets the promise and puts it into the event loop, the main thread runs out for the second time, and now the event loop has setTimeout2 and Promise2.
  4. For microtasks with queue-cutting macro tasks, print Promise2 and setTimeout2

The ultimate title

This will make it impossible for anyone to test you (too low a version of Node will have a different answer than a higher version). Don’t understand the comments will basically reply

console.log('1');
setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8')
})

setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')
    })
})
Copy the code

Node environment execution answer: 1, 7, 6, 8, 2, 4, 3, 5, 9, 11, 10, 12