1. What is an event loop? JS is single-threaded, so tasks are placed in a task queue. There are two types of tasks, synchronous and asynchronous. Perform synchronization first, then asynchronous.
console.log(1)
setTimeout(() => {
console.log(2)
}, 0)
Promise.resolve()
.then(() => {
console.log(3)
})
.then(() => {
console.log(4)
})
console.log(5)
Copy the code
The output is 1,5,3,4,2. Why? Synchronization task: console.log(1) console.log(5), followed by the code in promise, and finally setTimeout. Why is that? Because when fetching asynchronous queues, tasks are divided into macro tasks and micro tasks. Microtask: high priority, can jump the queue, not define first, execute first. Including: promise then, the observer, MutationObserver setImmediate macrotask: macro task, low priority, the first definition of execution, including: ajax, setTimeout and setInterval, event bindings. Because microtasks have a high priority, they are executed first, and then macro tasks are executed after all the microtasks are executed.