简体   繁体   English

如何停止 Javascript 中的无限循环?

[英]How do you stop an infinite loop in Javascript?

Let's say I accidentally wrote this:假设我不小心写了这个:

 do { } while (true);

...and then ran it. ...然后运行它。 Apart from killing your browser, is there a way to stop javascript execution (the equivalent of Ctrl+Break in basic, or Ctrl+C)?除了杀死你的浏览器,有没有办法停止 javascript 的执行(相当于基本的 Ctrl+Break 或 Ctrl+C)?

Normally, after about 30 seconds your browser asks if you want to stop the long-running script, but this doesn't always happen (as I just found out)!通常,大约 30 秒后,您的浏览器会询问您是否要停止长时间运行的脚本,但这并不总是发生(正如我刚刚发现的那样)!

FYI: A simple loop such as this: for (i=1; i > 0; ++i);仅供参考:一个简单的循环,例如: for (i=1; i > 0; ++i); will cause my browser to crash (Firefox 3.5b4).将导致我的浏览器崩溃(Firefox 3.5b4)。 I don't feel much like testing to see if it's any of my add-ons.我不太想测试它是否是我的任何附加组件。 Continuously restarting my browser isn't my idea of a fun Monday night.连续重启我的浏览器并不是我认为的一个有趣的星期一晚上。

I'm using Chome Version 45.0.2454.101我正在使用 Chome 版本 45.0.2454.101

At the top right hand corner, at the hamburger menu, click on More Tools > Task Manager, and then kill the tab from there.在右上角的汉堡菜单中,单击“更多工具”>“任务管理器”,然后从那里取消选项卡。 This is if attempting to close the tab fails.这是如果尝试关闭选项卡失败。 Otherwise a simple 'X' on the tab kills it.否则选项卡上的一个简单的“X”就会杀死它。

2018 update: 2018年更新:

In Chrome 67, if you have the DevTools open ( F12 ), you can end the infinite loop without killing the whole tab:在 Chrome 67 中,如果您打开了 DevTools ( F12 ),您可以结束无限循环而不杀死整个选项卡:

  • Go to the Sources panel and click "Pause script execution".转到“源”面板并单击“暂停脚本执行”。
  • Hold that same button and now select the "Stop" icon.按住相同的按钮,现在选择“停止”图标。

在此处输入图片说明

https://developers.google.com/web/updates/2018/04/devtools#stop https://developers.google.com/web/updates/2018/04/devtools#stop

At least with Chrome, you may be able to kill off the individual tab and not the whole application.至少在 Chrome 中,您可以关闭单个选项卡而不是整个应用程序。

Randolpho has also informed me that IE8 has similar functionality. Randolpho还告诉我 IE8 具有类似的功能。

ref: https://superuser.com/questions/92617/stop-never-ending-popup-alerts-in-firefox参考: https : //superuser.com/questions/92617/stop-never-ending-popup-alerts-in-firefox
Firefox is particularly problematic ... Firefox 尤其有问题...

Warning!警告! Caveat!警告! Do NOT run this!不要运行这个!

javascript:
    while (true) alert("irritated and exhausted - yet?");

This will go "infinite" and will NOT exhaust an internal timeout since the script will not chew up CPU time fast enough.这将“无限”并且不会耗尽内部超时,因为脚本不会足够快地消耗 CPU 时间。 In FF 11 this guarantees there will be no "unresponsive script" abortion opportunities.在 FF 11 中,这保证了不会有“无响应脚本”中止的机会。

Gracefully stopping just the offending script was possible and trivial in early browser versions, using manual intervention, without croaking and aborting the whole browser.在早期的浏览器版本中,使用手动干预优雅地停止有问题的脚本是可能的和微不足道的,而不会发出嘶嘶声和中止整个浏览器。 To not have such control is a major browser software design flaw.没有这样的控制是一个主要的浏览器软件设计缺陷。 Unreasonable dexterity and reflex are required to effect the manual motor mechanics of the "solutions" described in the reference.需要不合理的灵巧和反应能力来影响参考文献中描述的“解决方案”的手动运动机制。

Caveat: It is possible for scripts to go "infinite" w/o timing out AND w/o alert type prompts.警告:脚本有可能在没有超时和没有警报类型提示的情况下“无限”运行。 These are particularly pernicious and annoying.这些是特别有害和烦人的。 Basically, the scripts run slowly enough so that the CPU time cycle allotment of say 20 sec.基本上,脚本运行得足够慢,以至于 CPU 时间周期分配为 20 秒。 is stretched out over several minutes or hours or ..., before timing out, by suspension of execution pending resumption on an event trigger.被延长了几分钟或几小时,或者……,在超时之前,通过暂停执行等待事件触发器的恢复。 Instead of timing CPU cycles it would be far better for scripts to timeout on real world clocking.代替定时 CPU 周期,脚本在现实世界的时钟上超时会好得多。 (Ever notice how you cannot abort a script that is trying to retrieve content - but unsuccessfully - for constructing a page? In FF both the address bar buttons reload and cancel/stop are disabled though the tab at least can be closed.) Normal javascript Timeout() and setInterval() calls do not suffer from this and are conditioned so that while suspended, manual intervention is possible to abort them "gracefully". (有没有注意到您如何无法中止尝试检索内容但未成功的脚本来构建页面?在 FF 中,地址栏按钮reloadcancel/stop都被禁用,尽管该选项卡至少可以关闭。)普通 javascript Timeout()setInterval()调用不受此影响,并且是有条件的,因此在暂停时,手动干预可以“优雅地”中止它们。

Test environment for empirical observations:经验观察的测试环境:

window.navigator.userAgent=
Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:11.0) Gecko/20100101 Firefox/11.0

PS.附注。 the script剧本

for (i=1; i > 0; ++i);

will eventually trap on an overflow error when i exceeds the maximum value allowed.i超过允许的最大值时,最终会陷入溢出错误。

If you are using Chrome you can easily kill not responding tab.如果您使用的是 Chrome,您可以轻松杀死无响应标签。

When you see an infinite JavaScript loop occurred, do following steps:当您看到 JavaScript 无限循环发生时,请执行以下步骤:

1.If you have already opened another tab, go on that tab or Open a new one 1.如果您已经打开了另一个标签,请继续该标签或打开一个新标签

2.Press "Shift + Esc" to open Chrome's Task Manager 2.按“Shift + Esc”打开Chrome的任务管理器

3.Find your tab in the list (Should be with the most memory consumer in the list) and click "End Process" button. 3.在列表中找到您的选项卡(应该是列表中内存消耗最多的),然后单击“结束进程”按钮。


Navigating to another tab is important, because JavaScript will caught your key press and not do anything on that because of its infinite loop.导航到另一个选项卡很重要,因为 JavaScript 会捕获您的按键操作,并且由于其无限循环而不会对此执行任何操作。

Depends on the browser.取决于浏览器。 Some let you click the "stop" button to stop javascript execution.有些让您单击“停止”按钮来停止 javascript 执行。 Others don't.其他人没有。

I suggest the best way is to just kill the browser or tab entirely.我建议最好的方法是完全杀死浏览器或标签。

Most browsers have a "slow script performance" warning that comes up when an out of control javascript is taking a very long time to execute.大多数浏览器都有一个“脚本性能缓慢”警告,当一个失控的 javascript 需要很长时间来执行时,就会出现这个警告。 This warning dialog usually gives the option to kill the offending script.此警告对话框通常提供终止违规脚本的选项。

In Firefox在火狐浏览器中

Go to Developer Tools > Debugger , and click pause button.转到Developer Tools > Debugger ,然后单击暂停按钮。

在此处输入图片说明

In Chrome在 Chrome 中

Go to Developer Tools > Sources , and click pause button.转到Developer Tools > Sources ,然后单击暂停按钮。

在此处输入图片说明

From https://superuser.com/questions/92617/stop-never-ending-popup-alerts-in-firefox#comment93927_92617 , by anonymous :来自https://superuser.com/questions/92617/stop-never-ending-popup-alerts-in-firefox#comment93927_92617匿名

This isn't a satisfactory general-purpose solution, but with Greasmonkey (or maybe Ubiquity or Jetpack) you could overwrite window.alert with a function that calls window.confirm and optionally throw(s) an error, stopping all script execution, or toggles a flag to stop alerts.这不是一个令人满意的通用解决方案,但是使用 Greasmonkey(或者 Ubiquity 或 Jetpack),您可以使用调用 window.confirm 的函数覆盖 window.alert 并可选地抛出错误,停止所有脚本执行,或者切换标志以停止警报。 That might be useful if a site you keep going back to presents this behavior.如果您不断返回的站点呈现此行为,这可能很有用。

What I do when using Chrome and this happens is hitting shift+ctrl+esc to bring up the windows taskmanager.我在使用 Chrome 时所做的事情是按 shift+ctrl+esc 调出 Windows 任务管理器。 Then switch to the processes-tab and scroll through the chrome.exe processes(chrome has one process for each open tab) till I find one with significantly higher cpu usage than the oters.然后切换到进程选项卡并滚动浏览 chrome.exe 进程(chrome 每个打开的选项卡都有一个进程),直到我找到一个 CPU 使用率明显高于其他进程的进程。 It tends to have around 30% for me while all others have like 0-2% Then I'll just end that process.对我来说,它往往有大约 30%,而所有其他人都有 0-2% 然后我就结束这个过程。 Actually the same can be done by going to tools>taskmanager or shift+esc in chrome to open its custom taskmanager for its processes.实际上,同样可以通过在 Chrome 中转到工具>任务管理器或 shift+esc 来为其进程打开其自定义任务管理器来完成。 Might be easier to use that since it shows more info of the tabs.使用它可能更容易,因为它显示了更多的选项卡信息。

Last resort: close the browser from the OS.最后的手段:从操作系统关闭浏览器。 I had good results closing Chrome from the taskbar in Windows 10 while an infinite loop ran.在运行无限循环时,我从 Windows 10 的任务栏中关闭 Chrome 取得了很好的效果。 If that didn't work I would have killed the browser in Task Manager as above.如果那不起作用,我会如上所述在任务管理器中杀死浏览器。 On other OS's, of course the exact technique would vary.当然,在其他操作系统上,确切的技术会有所不同。 Infinite recursions are less a problem.无限递归不是问题。 All systems I've seen limit the size of the execution stack, and interrupt with a runtime error eventually once infinite recursion leads to stack overflow (no pun intended).我见过的所有系统都会限制执行堆栈的大小,并且一旦无限递归导致堆栈溢出(没有双关语),最终会以运行时错误中断。

大多数体面的浏览器确实会显示“无响应脚本”警告..​​....如果没有,我想你最好的做法是找出警告没有弹出的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM