为什么setTimeout(..,0)不立即执行? [英] Why doesn't setTimeout(.., 0) execute immediately?

查看:382
本文介绍了为什么setTimeout(..,0)不立即执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var timeout = setTimeout(function(){
     console.log("I'm message from timeout");
},0);

console.log("I'm message from outside timeout");

//1. I'm message from outside timeout
//2. I'm message from timeout

为什么内部指令不会先执行,尽管设置了setTimeout时间0?我使用各种时间,包括0 / null,我想知道如何保留setTimeout对象并使用流执行其指令。

Why the inner instructions don't execute first, despite setting setTimeout time on 0? I use various times including 0/null and I'm wondering how to both retain setTimeout object and execute its instructions with the flow.

推荐答案

Javascript代码仅在一个线程上运行。 setTimeout 计划稍后运行的函数。所以在js中当所有当前运行的代码完成执行时, event 循环将查找任何其他事件。
所以 setTimeout(.. 0)将使代码在当前循环之后运行。

Javascript code runs only on one thread. setTimeout schedules a function to run later. So in js when all currently running code finish its execution , event loop will look for any other event. So setTimeout( .. 0) will make code run after the current loop.

console.log(我是来自外部超时的消息); 将首先安排执行。一旦完成 setTimeout 将被执行

console.log("I'm message from outside timeout"); will be first scheduled to executued. As soon as it finish the setTimeout will be executed

所以底线 setTimeout(myfunction) ,0)将在当前执行函数后运行myfunction 0ms。 &安培;在你的情况下,当前的执行循环是

So bottom line setTimeout(myfunction ,0) will run myfunction 0ms after currently executing function. & in your case the current execution loop is

console.log("I'm message from outside timeout");

如果你添加另一个console.log(我是来自timeout1以外的消息);
所以当前事件循环将首先记录

If you add another console.log("I'm message from outside timeout1"); so current event loop will first log

I'm message from outside timeout
I'm message from outside timeout1

在开始 setTimeout 功能之前。

注意 setTimeout 的最小超时时间为4毫秒。您可以查看此 Stackoverflow主题以了解有关它的更多信息

NOTE setTimeout has a minimum timeout of 4ms . You can look at this Stackoverflow thread to know more about it

这篇关于为什么setTimeout(..,0)不立即执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆