Synchronous and asynchronous

We all know one line code is executed, but sometimes if the code in front of the need to take a longer time, so we can make the back of the first code execution, and won’t let the page load slowly, then JavaScript is single-threaded language, but he has a concept of synchronous and asynchronous, a brief understanding of the concept of synchronous and asynchronous

  • Synchronous: A function is synchronous if the caller gets the expected result when it returns.
  • Asynchronous: A function is asynchronous if the caller does not get the expected result when it returns, but needs to get it in the future by some means.

Why is JavaScript single threaded, so we need to talk about the benefits of single threading

The js engine thread and the page rendering thread are mutually exclusive because JS can modify the DOM structure. If the UI thread is still working while JS is executing, it may result in unsafe RENDERING of the UI. Thanks to the fact that JS is single-threaded, It saves running memory and context switching time

Event loop

  • Synchronous and asynchronous tasks

All synchronization task in the execution stack, JavaScript stack sequentially executed in the method, each time to execute a method that will be generated for it unique execution environment (context), when this method completes, will destroy the current execution environment, and pop up this method from the stack, and then continue with the next method. All asynchronous tasks are placed in the task queue and executed one by one. Therefore, the synchronization task is executed first, and then asynchronous tasks are executed in the task queue after the synchronization task is complete

Let’s look at a simple example

console.log('Code starts executing');
setTimeout(function(){
    console.log('Timer started')});console.log('End of code execution');
Copy the code

The result is: the code starts executing -> the code ends -> the timer starts, because setTimeout is an asynchronous task, so it is executed after the timeout.

Let’s look at an example

setTimeout(function(){
    console.log('2')});for(let i =0; i<3000; i++){console.log(1);
}
console.log(3);
Copy the code

It prints 3000 1’s, 3’s, and then 2’s, which means it executes the synchronous task first, waits until the synchronous task is complete, and then executes the asynchronous task in the task queue

Macro and micro tasks

Task queues can also be broken up into macro tasks and microtasks, which are a follower that follows the current macro task, executing code to one microtask after another.

Common macro tasks include: Script (overall code), setTimeout, setInterval, I/O, UI interaction events, setImmediate(node.js environment), Ajax, reading files

Microtasks include Promise, MutaionObserver, process.nexttick (node.js environment); Priority Process.nexttick > promise.then > setTimeout > setImmediate

We need to keep these common macro and micro tasks in mind

  • process.nextTick

console.log('Code starts executing');
setTimeout(() = > {
    console.log('timeout');
}, 0);

Promise.resolve().then(() = > {
    console.error('promise')
})

process.nextTick(() = > {
    console.error('nextTick')})console.log('End of code execution');
Copy the code

Result: Start code execution -> end code execution -> nextTick -> Promise -> timeout

Process.nexttick (), mentioned above, is a newly introduced task queue in Node that executes immediately at the end of the synchronization phase before moving on to the next phase.

  • await

With async await async function returns a Promise object, you can add a callback function using the then method. When a function executes, it returns as soon as it encounters await, waits for the asynchronous operation to complete, and then executes the following statement in the function body. Await produces a microtask (promise. then is a microtask) when the function following await completes execution. It is the execution of await, directly out of async function, to execute other code. When the rest of the code is finished, go back to async to execute the rest of the code,

  • setImmediate

Classic topic

Let’s take a look at some classic examples and see if you can do it

console.log('script start')

async function async1() {
console.log('async1'); / / synchronize
await async2()
console.log('async1 end') / / asynchronous
}
async function async2() {
console.log('async2 end')
}
async1()
setTimeout(function() {
console.log('setTimeout')},0)
process.nextTick(() = > {
    console.error('nextTick')})new Promise(resolve= > {
console.log('Promise') / / synchronize
resolve()
})
.then(function() {
console.log('promise1')
})
.then(function() {
console.log('promise2')})console.log('script end')
Copy the code

This is not printed in the new version of Chrome, Script start -> async1 -> async2 end -> Promise -> script end -> nextTick -> async1 end -> async1 end -> Promise1 -> promise2 -> setTimeout

  • First execute the synchronization code, outputscript start.
  • callasync1The outputasync1 .
  • callAsync2 outputasync2 end `,
  • When setTimeout is encountered, a macro task is generated
  • Execute the Promise, outputPromiseThen the outputscript end All synchronous tasks are finished, and then go to the asynchronous task queue
  • Execute process.nextTick to generate the first microtask
  • Perform the microtask generated after awaitasync1 end
  • When then is encountered, new microtasks are generated
  • Starts executing the microtask queue generated by the current macro task, and outputspromise1, the microtask encounters then, resulting in a new microtask
  • Perform the resulting microtask, outputpromise2, the current microtask queue completes
  • Finally, execute the next macro task, setTimeout, outputsetTimeout

Conclusion:

A microtask is a follower of the current macro task, and the code executes to one microtask after another

Task Priority Process.nexttick > promise.then > setTimeout > setImmediate

Order of execution:

- Execute synchronous code first, - when all synchronous code is executed, the execution stack is empty, to check whether there is any asynchronous code to execute - execute all microtasks - When all microtasks are executed - start the next round of event-loop, Perform asynchronous code synchronization in macro tasks --> asynchronous --> microtask --> macro taskCopy the code