javascript setTimeout(function(){console.log(3)}, 0); 它的值为 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28115853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:26:13  来源:igfitidea点击:

setTimeout(function(){console.log(3)}, 0); it has value 0

javascriptfunction

提问by

When I execute the below code in the console I am getting as 1,4, undefined 3,2.

当我在控制台中执行以下代码时,我得到 1,4, undefined 3,2.

I would like to know why its not executing as 1,3,4and 2since in setTimeout(function(){console.log(3)}, 0);the milliseconds param is 0.

我想知道为什么它不执行1,3,42因为在setTimeout(function(){console.log(3)}, 0);毫秒参数中是0.

    (function() {
        console.log(1); 
        setTimeout(function(){console.log(2)}, 1000); 
        setTimeout(function(){console.log(3)}, 0); 
        console.log(4);
    })();

回答by nril

Here's a great explanation by John Resig: http://ejohn.org/blog/how-javascript-timers-work/
But the bottom line is console.log(1) and (4) are executed 'in-line' and 2 and 3 are placed in the event queue, and don't get executed until the all of the in-line code is executed. So, even though the delay is 0 for (3), it still occurs after all statements are executed.
I'm not getting the undefined message when I test you code either.

这是 John Resig 的一个很好的解释:http: //ejohn.org/blog/how-javascript-timers-work/
但底线是 console.log(1) 和 (4) 是“内嵌”执行的,而 2和 3 被放置在事件队列中,并且在所有内嵌代码执行完毕之前不会被执行。因此,即使 (3) 的延迟为 0,它仍然会在所有语句执行后发生。
当我测试你的代码时,我也没有收到未定义的消息。

回答by ThiefMaster

The undefinedis, as mentioned in a comment, the return value of your function.

undefined是,作为一个评论,你的函数的返回值提及。

The reason why 4comes before 3is simply that there is no parallelism in JavaScript so the timer callbacks cannot execute until your function has returned.

4出现在之前的原因3很简单,因为 JavaScript 中没有并行性,因此在您的函数返回之前,计时器回调无法执行。

回答by Hacketo

Short Answer : the undefinedcome from the result of the executed statement in your javascript console, the function return nothing, so undefined

简短回答:undefined来自 javascript 控制台中执行语句的结果,该函数不返回任何内容,因此未定义

Let try to decompose this:

让我们尝试分解它:

  1. console.log(1);// 1
  2. console.log(4);// 4
  3. the code you executed return undefined
  4. setTimeout(function(){console.log(3)}, 0);// 3Executed the next stack
  5. setTimeout(function(){console.log(2)}, 1000);// 21 sec after
  1. console.log(1);// 1
  2. console.log(4);// 4
  3. 你执行的代码返回 undefined
  4. setTimeout(function(){console.log(3)}, 0);//3执行下一个栈
  5. setTimeout(function(){console.log(2)}, 1000);// 21 秒后

Edit : Test this

编辑:测试这个

var a = (function(){})(); // print undefined, a is also undefined, no returned value