我们知道alert()是阻塞式的,但是一下代码执行顺序有问题
执行顺序有问题
(()=>{
for(let i = 0; i < 5; i++){
setTimeout(() => alert(i), 1000);
}
})()
结果: 0,3,2,1,4
执行顺序没问题
(()=>{
for(let i = 0; i < 5; i++){
setTimeout(() => console.log(i), 1000);
}
})()
结果:0,1,2,3,4
这是为什么呢?
PHPz2017-04-17 16:40:12
It is recommended to take a look at the operating principle of setTimeout
If you don’t click OK when alert 0, wait 5s (if the thread is idle, you may need to wait 10s or more) and then click again, you will find that the order is normal
The reason is that setTimeout is in the code. If the process is occupied, when the process is idle, it will skip this time and execute the next time