What triggers the event loop?
- Js is single threaded, but when JS wants to request data from the back end, the front end can still manipulate the buttons. This is because browsers have other functions besides the JS engine, such as Web APIs, GUI rendering processes…
Second, the rules
- Synchronous events are placed in the execution stack, and asynchronous events are placed in the execution queue. The execution of the events in the execution stack is completed first, and then the events in the execution queue are taken out in a certain order and put into the execution stack
1. The execution stack
- Events in the execution stack are executed last in, first out
2. Execute the queue
- The events in the execution queue are divided into micro task queue and macro task queue, micro task queue and then macro task queue
- Microtask queues: DOM operations, Ajax, setTimeout, etc
- Macro task queues: Promise, nextTick, etc
3. Summary
- Stack after queue, queue micro macro, micro render, finally execute macro.
Three, related topics
1. Only synchronization tasks are performed
function foo() {
bar();
console.log('foo');
}
function bar() {
baz();
console.log('bar');
}
function baz() {
console.log('baz');
}
foo();
/* baz bar foo */
Copy the code
2. When you have microtasks
- The promise functions created using the new keyword are automatically executed, while the asynchronous tasks are in. Then
function foo() {
console.log('foo');
}
console.log('global start');
new Promise((resolve, reject) = > {
resolve();
console.log('promise');
}).then(() = > {
console.log('promise then');
}).catch(() = > {
console.log('error');
})
foo();
console.log('global end');
/* global start promise foo global end promise then */
Copy the code
3. When you have microtasks & macro tasks
function foo() {
console.log('foo');
}
console.log('global start');
setTimeout(() = > {
console.log('setTimeout: 0s');
}, 0);
new Promise(resolve= > {
console.log('promise');
resolve();
}).then(() = > {
console.log('promise then');
})
foo();
console.log('global end');
/* global start promise foo global end promise then setTimeout: 0s */
Copy the code
4. Async&await
- promise async await
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(() = > {
console.log('setTimeout');
},0)
async1();
new Promise((resolve) = > {
console.log('promise1');
resolve();
}).then(() = > {
console.log('promise2');
})
console.log('script end');
/* script start async1 start async2 promise1 script end async1 end promise2 setTimeout */
Copy the code