javascript - 为什么0秒的setTimeout最后完成

标签 javascript asynchronous synchronous

<分区>

所以我想出了这个例子,我无法理解为什么 0 秒的 setTimeout 是最后一个要执行的

function waitThreeSeconds() {
  setTimeout(function() {
    console.log("Finished Function");
  }, 0);
}

function clickHandler() {
  console.log("Clicked");
}

document.addEventListener('click', clickHandler);

waitThreeSeconds();

//waiting 5 seconds 
var ms = 5000 + new Date().getTime();
while (new Date() < ms) {}


console.log('Finished Execution');

如果 setTimeouts 回调确实被添加到队列中,为什么每次我执行单击事件时它都比 setTimeout 的回调更早地添加到队列中。直到全局执行上下文('main')从堆栈中弹出

最佳答案

是的,@KenY-N 在问题评论中所说的是真的。

我之前就 promise 回调 ( https://stackoverflow.com/a/40882544/5217142 ) 回答过这个问题:

In HTML terms, the event loop for a page or set of pages from the same domain can have multiple task queues. Tasks from the same task source always go into the same queue, with the browser choosing which task queue to use next.

Tasks to run timer call backs come from the timer task source and go in the same queue....

这里的区别是你问的是点击事件的任务队列优先级是否高于定时器回调的任务队列优先级。

通过检查,您的代码显示答案是肯定的:在您尝试过的浏览器中,点击事件的任务队列优先于计时器回调的任务队列。

关于javascript - 为什么0秒的setTimeout最后完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53405401/

相关文章:

javascript - 获取在 JQuery 中调用函数的元素?

javascript - 修复两个高度之间的 div 位置

javascript - ajax 调用/Angular 中的嵌套循环

javascript - 我如何使用angularjs从异步调用中定义全局变量?

javascript - 同步与异步 Nodejs

javascript - 从另一个 iframe 更改 iframe 源

c# - 具有同步和异步调用者的同步方法中的 Thread.Sleep 或 Task.Delay

c# - 在键盘事件中使用 CancellationToken 调用 Task.Delay 时出现 TaskCanceledException

jquery - 使用 jQuery 发出同步请求时,如何防止浏览器锁定(或显示等待符号)?