【发布时间】:2016-08-09 15:03:26
【问题描述】:
console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
console.log('three');
输出是: '一' '三' '两个'
幕后发生了什么?为什么代码会产生这个输出?
【问题讨论】:
标签: javascript
console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
console.log('three');
输出是: '一' '三' '两个'
幕后发生了什么?为什么代码会产生这个输出?
【问题讨论】:
标签: javascript
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 队列如何工作的链接,检查一下!
【讨论】:
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
(*):在这两者之间可能有其他回调被排队调用。
【讨论】:
Javascript 使用事件循环来执行异步代码。 Javascript 是单线程的,因此所有回调都使用回调队列一一运行。代码以一系列“滴答声”运行。这意味着队列处理仅在前一个完成时发生。这里 setTimeout 注册一个回调并返回。有下一行代码要执行,因此它们将首先在此调用堆栈中执行。在没有要执行的内容之后,注册的回调才会被执行。
【讨论】: