为什么 setTimeout(code...,1) 先执行 setTimeout(code... ,0)?
我测试了这段代码,我期望的结果是首先获得 Chicken 日志,但我错了,每次运行此代码时,我都会先获得 Egg 日志,有人知道这里发生了什么吗?
setTimeout(() => {
console.log("Egg");
}, 1);
setTimeout(() => {
console.log("Chicken");
}, 0);
编辑: 请注意,如果延迟分别为 101 毫秒和 100 毫秒,则行为会有所不同,因此即使计时器上的差异仍然是 1 毫秒,行为也会发生变化
I tested this code and the result I expected was getting the Chicken log first, but I was wrong, everytime I run this code I get the Egg log first, does anybody knows whats going on here?
setTimeout(() => {
console.log("Egg");
}, 1);
setTimeout(() => {
console.log("Chicken");
}, 0);
Edit:
Notice that this behaves differently if those delays are 101ms and 100ms respectively, so the behavior changes even if the difference on the timer is still 1ms
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
计时器在执行指定函数或代码之前应等待的时间(以毫秒为单位)。 1000ms 将是 1 秒,因为你输入的参数是 1ms,JS 只是按照写入的顺序显示它,因为 1ms 和 0ms 是可比较的。此外,您可以使用 async-await 来等待需要更长时间的任务。例如,
在此示例中,Chicken 将尽快打印,但为了打印 Egg,它将等待 1 秒(1000 毫秒)并最终打印 Egg。
The time is in milliseconds that the timer should wait before the specified function or code is executed. 1000ms will be 1 sec and since your input to a parameter was 1ms JS just displayed it in the order it was written because 1ms and 0ms were comparable. Moreover, you can use async-await to wait for tasks that would take longer. For instance,
In this example, Chicken will be printed asap however in order to print Egg it will wait for 1 sec (1000ms) and finally print Egg.