您的位置:首页 > 其它

setTimeout的工作原理

2016-03-22 08:56 183 查看
<span style="font-family:Courier New;color:#a9b7c6;"><span style="font-size: 10.5pt; background-color: rgb(43, 43, 43);"><script>
var x = 1;
setTimeout(function(){
x = 2;
console.log("setTimeout----------"+x);
},0);
console.log("outer-----------"+x);
</script>                    
</span></span> 
</pre><pre name="code" class="html">输出如下图:
<img src="http://img.blog.csdn.net/20160322090139965?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" style="font-family: 'Courier New'; font-size: 10.5pt;" alt="" />
原因是:setTimeout在线程空闲的时候才开始执行。
设置为0毫秒后执行,即系统空闲之后,隔0毫秒将函数加入执行队列。
因此在outer的输出之后系统空闲,输出setTimeout内的log。

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: