我在 Stack Overflow 上发现了这个在 TypeScript 和 JavaScript 中休眠的简洁小代码:
async function sleep(ms : number) {
return new Promise<void>(resolve => setTimeout(resolve, ms));
}
我这样使用它:
while(true) {
updateBackground();
await sleep(1000);
}
潜在的问题是 sleep 函数将“then”添加到调用堆栈中,并且看起来每次 sleep 调用的调用堆栈都变得越来越大。我认为堆栈空间迟早会用完。
有什么好的办法可以解决吗?我怎么 sleep ?
最佳答案
while
循环的每次迭代都应刷新调用堆栈。您确定正在查看实际的调用堆栈吗?
您是否检查了开发人员工具“源”选项卡右侧栏“调用堆栈”下的内容。它应该报告为空。它不应该无限增长。
在下面的代码中,堆栈的大小只能为三:
const sleep = async (ms) =>
new Promise(resolve => setTimeout(resolve, ms));
const printTime = () => {
console.log(`Current time: ${new Date().toLocaleTimeString()}`);
};
const updateBackground = () => {
printTime();
};
(async () => {
while (true) {
updateBackground();
await sleep(1000);
}
})();
.as-console-wrapper { top: 0; max-height: 100% !important; }
在 printTime
内放置一个断点应显示以下堆栈:
updateBackground // printTime call within updateBackground
(anonymous) // call from within the while-loop
(anonymous) // the top-level await or IIFE
关于javascript - 如何在有限调用堆栈上的 JavaScript 中休眠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74464292/