Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么即使setTimeout设置为0 delay也会有延迟?_Javascript - Fatal编程技术网

Javascript 为什么即使setTimeout设置为0 delay也会有延迟?

Javascript 为什么即使setTimeout设置为0 delay也会有延迟?,javascript,Javascript,输出为: “一个” “三个” “两个” 幕后发生了什么?为什么代码会生成此输出?setTimeout()不要“在声明后的X秒内”执行给定函数,在幕后,此方法将给定函数放入堆栈,在执行上下文中的代码执行后的X秒内执行,在本例中,当代码的第1行和第4行被执行时” 一个例子 console.log('one'); setTimeout(function() { console.log('two'); }, 0); console.log('three'); //输出:“一”、“三”、“二”、“四

输出为: “一个” “三个” “两个”

幕后发生了什么?为什么代码会生成此输出?

setTimeout()
不要“在声明后的X秒内”执行给定函数,在幕后,此方法将给定函数放入堆栈,在执行上下文中的代码执行后的X秒内执行,在本例中,当代码的第1行和第4行被执行时”

一个例子

console.log('one');
setTimeout(function() {
  console.log('two');
}, 0);
console.log('three');
//输出:“一”、“三”、“二”、“四”

幕后:

在执行上下文中

setTimeout(function() {
  console.log('four');
}, 10);
console.log('one');
setTimeout(function() {
  console.log('two');
}, 0);
console.log('three');
在执行上下文之后
setTimeout(fn,ms)
按第二个参数的顺序排序,以毫秒为单位:

console.log('one');
console.log('three');

编辑:已经搜索了在下一个响应中以图形方式解释javascript浏览器队列工作原理的链接,请查看它!

javascript解释器在一个大事件循环中以单线程方式运行所有代码;您调用的
setTimeout
将回调作为另一个事件排队,在当前事件发生时立即执行完成t代码(以及之前可能已排队的其他代码)

所以解释器执行它的方式如下:

console.log('two');//0 ms after the execution context has been executed.
console.log('four'); //10ms after the execution context has been executed
获取并执行下一个事件
调用您的全局代码
调用console.log('one');
调用setTimeout(func);
调用console.log('three');
从全局代码返回
获取并执行下一个事件*
调用setTimeout回调
调用console.log('two');
从setTimeout回调返回

(*):在这两者之间可能有其他回调被排队调用。

Javascript使用事件循环执行异步代码。Javascript是单线程的,因此所有回调都使用回调队列逐个运行。代码以一系列“滴答声”运行“。这意味着队列处理仅在前一个队列处理完成时发生。这里setTimeout注册回调并返回。下一行代码将被执行,因此它们将首先在此调用堆栈中执行。在没有要执行的内容之后,只会执行注册的回调

此处给出了直观的解释:

您可以在这些伟大的链接上阅读,谢谢!
get and execute next event
  calling your global <script> code
    calling console.log('one');
    calling setTimeout(func);
    calling console.log('three');
  returning from your global <script> code
get and execute next event*
  calling setTimeout callback
    calling console.log('two');
  returning from setTimeout callback