如何退出 JavaScript 中的无限循环?
是否有可能完全停止无限循环的运行?
现在我正在做这样的事情:
var run = true;
loop ({
if(run) {
whatever
}
}, 30),
然后,当我想停止它时,我将 run
更改为 false
,当我想要时,将其更改为 true
重新开始吧。
但无论我做什么,循环总是在运行。它只是不执行里面的代码。
有没有办法完全阻止它?并在我想要的时候让它重新开始?
Is it possible to stop an infinite loop from running at all?
Right now I am doing something like this:
var run = true;
loop ({
if(run) {
whatever
}
}, 30),
Then when I want to stop it I change run
to false
, and to true
when I want to start it again.
But the loop is always running whatever I do. It just not executing the code inside.
Is there a way to stop it completely? and make it start again when I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果我正确理解你的问题,你需要的是
break
关键字。 这里是一个示例。If I am understanding your question correctly, what you need is the
break
keyword. Here's an example.SetInterval 会给你一个可以取消的循环。
将间隔设置为一个较小的值并使用clearinterval取消它
SetInterval will give you a loop you can cancel.
Set the interval to a small value and use clearinterval to cancel it
它可能不完全是您正在寻找的,但您可以尝试
setInterval
。
var IntervalId = setInterval(myFunc, 0);
setInterval 也不会阻塞页面。您可以使用
clearInterval
清除间隔。It may not be exactly what you are looking for, but you could try
setInterval
.var intervalId = setInterval(myFunc, 0);
setInterval will also not block the page. You clear the interval as shown with
clearInterval
.使用 while 循环
当
run
为 false 时,循环退出。将其放入函数中,并在想要再次开始循环时调用它。Use a while loop
When
run
is false the loop exits. Put it in a function and call it when you want to begin the loop again.问题是 javascript 只有一个线程可以运行。这意味着当你无限循环时,不会发生任何其他事情。因此,您的变量不可能改变。
解决此问题的一种方法是使用
setTimeout
进行循环,并传递给它一个非常小的时间。例如:这将使其他操作有可能利用该线程并可能更改标志。
The problem is that javascript only has a single thread to run on. This means that while you are infinitely looping nothing else can happen. As a result, it's impossible for your variable to ever change.
One solution to this is to use
setTimeout
to loop with a very small time passed to it. For example:This will give the possibility for other actions to make use of the thread and potentially change the flag.