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

Why doesn't setTimeout(.., 0) execute immediately?

本文关键字:执行 setTimeout 为什么      更新时间:2023-09-26
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)将在当前执行函数后运行myfunction 0ms。

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

如果添加另一个控制台.log("我是来自外部超时1的消息");所以当前事件循环将首先记录

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

在启动setTimeout功能之前。

注意setTimeout的最小超时为 4ms 。你可以看看这个 堆栈溢出线程 了解更多有关它的信息