英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论