How do you stop an infinite loop in Javascript?

Viewed 90633

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)?

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)!

FYI: A simple loop such as this: for (i=1; i > 0; ++i); will cause my browser to crash (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.

12 Answers

At least with Chrome, you may be able to kill off the individual tab and not the whole application.

Randolpho has also informed me that IE8 has similar functionality.

If you are using Chrome you can easily kill not responding tab:

  1. Switch to any other tab
  2. Press Shift + Esc to open Chrome's Task Manager
  3. Find your tab in the list (Should be the most memory consumer)
  4. Click End Process

Important: Navigating to another tab is important, because if you are on the original tab JavaScript will make the browser unable to process your key press and do nothing because of its infinite loop.

Depends on the browser. Some let you click the "stop" button to stop javascript execution. 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. This warning dialog usually gives the option to kill the offending script.

In Firefox

Go to Developer Tools > Debugger, and click pause button.

enter image description here

In Chrome

Go to Developer Tools > Sources, and click pause button.

enter image description here

most decent browsers do show an "unresponsive script" warning... If not, I guess your best course of action would be to find out why the warning is not popping up.

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. 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).

Related