我在Viusal Studio代码中运行了非常基本的javascript代码。但是我没有看到回调函数被触发。我试图了解setTimeout()在javascript中的工作方式。我正在Visual Studio代码中运行以下代码(在名为test.js的文件中),如下所示:节点test.js'use strict'let timerexpired = false;setTimeout( function() {console.log(`setting timerexpired to true...`); timerexpired = true; }, 5000);while(1) { console.log(`timerexpired = `, timerexpired); if (timerexpired) { console.log(`timer expired. Resume execution`); break; } else { console.log(`keep on spinning`); }}预期循环将在5000毫秒后中断。但它会继续旋转,输出为“继续旋转”
2 回答

鸿蒙传说
TA贡献1865条经验 获得超7个赞
setTimeout
实际上,当您致电或进行任何阻止操作时,它实际上已添加到事件表中,而不会立即执行。
只有在调用堆栈为空之后,事件循环才检查事件表以查看是否有任何等待,并将其移至调用堆栈。
为了更好地理解这一点,请检查以下示例:
setTimeout(() => console.log('first'), 0) console.log('second')
您可能会认为该first
日志将在之前记录second
,但实际上它second
是最先记录的。
在您的示例中,调用堆栈永远不会为空,因此setTimeout
不会真正按预期工作。
您可能想检查一下,这将使您对幕后发生的事情有个更好的了解。
添加回答
举报
0/150
提交
取消