如何在JS中创建一个永久循环而不冻结

huangapple go评论61阅读模式
英文:

How to make a forever loop in JS not freeze

问题

我正在开发一个基于Google Blockly的基于块的编程语言。我需要创建一个无限循环块,用于制作游戏。

我尝试了一个while (true)循环,但它卡住了。有没有办法创建一个不会卡住并允许其他脚本运行的无限循环?

谢谢!

英文:

I'm working on a block based programming language based of of Google's Blockly. I need to make a block that loops the contents forever, for making games.

I tried a while (true) loop but it froze. Is there any way to make a forever loop that won't freeze and will let other scripts run?

Thanks!

答案1

得分: 0

查看 setTimeout():https://developer.mozilla.org/en-US/docs/Web/API/setTimeout

类似于这样无限循环而不阻塞主线程(你应该设计一种方法在某个时刻中断循环):

function doSomeStuff() {
  // 做一些事情…
  setTimeout(() => {
    doSomeStuff();
  }, 1000);
}
英文:

check setTimeout() : https://developer.mozilla.org/en-US/docs/Web/API/setTimeout

Something like that to loop indefinitely without blocking the main thread (you should probably design a way to break the loop at some point) :

function doSomeStuff() {
  // do some stuff…
  setTimeout(() => {
    doSomeStuff();
  }, 1000);
}

huangapple
  • 本文由 发表于 2023年6月1日 21:38:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定