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
setTimeout(function(){console.log(3)}, 0); it has value 0
提问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,4
and 2
since in setTimeout(function(){console.log(3)}, 0);
the milliseconds param is 0
.
我想知道为什么它不执行1,3,4
,2
因为在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 undefined
is, as mentioned in a comment, the return value of your function.
的undefined
是,作为一个评论,你的函数的返回值提及。
The reason why 4
comes before 3
is 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 undefined
come from the result of the executed statement in your javascript console, the function return nothing, so undefined
简短回答:undefined
来自 javascript 控制台中执行语句的结果,该函数不返回任何内容,因此未定义
Let try to decompose this:
让我们尝试分解它:
console.log(1);
//1
console.log(4);
//4
- the code you executed return
undefined
setTimeout(function(){console.log(3)}, 0);
//3
Executed the next stacksetTimeout(function(){console.log(2)}, 1000);
//2
1 sec after
console.log(1);
//1
console.log(4);
//4
- 你执行的代码返回
undefined
setTimeout(function(){console.log(3)}, 0);
//3
执行下一个栈setTimeout(function(){console.log(2)}, 1000);
//2
1 秒后
Edit : Test this
编辑:测试这个
var a = (function(){})(); // print undefined, a is also undefined, no returned value