promise,settimeout,宏任务,微任务,同步任务,异步任务
/**
* @file promise,settimeout,宏任务,微任务问题
*/
setTimeout(() => {
console.log(1);
}, 20);
for (var i = 0; i < 10000000; i++) {}
console.log(2);
setTimeout(() => {
console.log(3);
}, 0);
Promise.resolve().then(() => {
console.log(4);
});
new Promise((resolve, reject) => {
console.log(5);
resolve();
console.log(6);
}).then(() => {
console.log(7);
});
console.log(8);
// 大部分人的电脑运行之后的结果如下:
// 2
// 5
// 6
// 8
// 4
// 7
// 1
// 3
// 答案:最后两位 1 和 3 的位置是不确定的 ,取决于for循环执行的时间
// for执行时间 >= 20毫秒,1,3 否则 3,1
// 验证方法:修改for的遍历次数,比如,改为i < 100,就是结果就是3,1
解题需要知道的知识:
-
- 函数 setTimeout 接受两个参数:待加入队列的消息和一个时间值(可选,默认为0)。这个时间值代表了消息实际加入到队列的最小延迟时间。
-
- 如果队列中没有其他消息并且栈为空,在这段时间过去之后,消息会被马上处理。但是,如果有其他消息,setTimeout 消息必须等待其他消息处理完。
-
- 因此第二个参数仅仅表示最少延迟时间,而非确切的等待时间。