javascript - 为什么 setTimeout(.., 0) 不立即执行?

标签 javascript settimeout

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 对象并随流程执行其指令。

最佳答案

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

console.log("I'm message from outside timeout"); 将首先安排执行。一旦它完成 setTimeout 将被执行

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

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

如果再添加一个console.log("I'm message from outside timeout1"); 所以当前事件循环将首先记录

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

在开始 setTimeout 函数之前。

注意 setTimeout 的最小超时为 4 毫秒。你可以看看这个Stackoverflow thread了解更多

关于javascript - 为什么 setTimeout(.., 0) 不立即执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36904773/

相关文章:

javascript - Angular 和 Tel 绑定(bind)返回错误数据

javascript - 使用 Rails 后端渲染 Ember 组件(谷歌折线图)

javascript - 在 HTML 页面之间维护 Javascript 变量以发送到数据库?

javascript - 变量在 Controller 中更新但未在 HTML 中更新?

javascript - 无法让 Javascript 超时事件执行

javascript - 从 javascript 函数返回一个值,然后执行其中的代码

javascript - 位函数返回未定义

javascript - sinon server.autoRespond

javascript - 为什么 Underscore.js 有延迟功能?

javascript - jQuery 显示 setTimeout 定时器