search

Home  >  Q&A  >  body text

javascript - 关于js,alert()阻塞的问题

我们知道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

这是为什么呢?

天蓬老师天蓬老师2872 days ago674

reply all(2)I'll reply

  • PHPz

    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

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 16:40:12

    Post a link, you should be enlightened after reading it

    reply
    0
  • Cancelreply