【问题标题】:Why there is a delay even though setTimeout is set to 0 delay? [duplicate]为什么即使 setTimeout 设置为 0 延迟也会有延迟? [复制]
【发布时间】:2016-08-09 15:03:26
【问题描述】:
console.log('one');
setTimeout(function() {
  console.log('two');
}, 0);
console.log('three');

输出是: '一' '三' '两个'

幕后发生了什么?为什么代码会产生这个输出?

【问题讨论】:

标签: javascript


【解决方案1】:

setTimeout()don`t execute the given function "In X seconds after that you declare it", 在幕后,此方法将给定函数放入堆栈中,然后在 X 秒后执行执行上下文已被执行,在这种情况下,当您的代码的第 1 行和第 4 行已经执行时"

一个例子

setTimeout(function() {
  console.log('four');
}, 10);
console.log('one');
setTimeout(function() {
  console.log('two');
}, 0);
console.log('three');

//输出:'一','三','二','四'

幕后:

在执行上下文中

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

在执行上下文之后 setTimeout(fn, ms)按第二个参数排序,单位毫秒:

console.log('two');//0 ms after the execution context has been executed.
console.log('four'); //10ms after the execution context has been executed

编辑:一直在搜索下一个响应中以图形方式解释 javascript-browser 队列如何工作的链接,检查一下!

【讨论】:

    【解决方案2】:

    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
    

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

    【讨论】:

      【解决方案3】:

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

      这里给出了直观的解释: http://latentflip.com/loupe/?code=Y29uc29sZS5sb2coJ29uZScpOwpzZXRUaW1lb3V0KGZ1bmN0aW9uKCkgewogIGNvbnNvbGUubG9nKCd0d28nKTsKfSwgMCk7CmNvbnNvbGUubG9nKCd0aHJlZScpOw%3D%3D!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D

      【讨论】:

      • 很好的链接,谢谢!
      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多