Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you stop an infinite loop in Javascript?

Tags:

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

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.

like image 542
nickf Avatar asked May 25 '09 04:05

nickf


People also ask

How do you stop a loop in JavaScript?

You use the break statement to terminate a loop early such as the while loop or the for loop. If there are nested loops, the break statement will terminate the innermost loop. You can also use the break statement to terminate a switch statement or a labeled statement.

How do you stop a loop from running?

The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop. To exit a function, use return .


1 Answers

2018 update:

In Chrome 67, if you have the DevTools open (F12), you can end the infinite loop without killing the whole tab:

  • Go to the Sources panel and click "Pause script execution".
  • Hold that same button and now select the "Stop" icon.

enter image description here

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

like image 157
Sphinxxx Avatar answered Oct 05 '22 05:10

Sphinxxx