Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if i make a mistake in code and cause an infinite loop in javascript and it keeps on calling alert(), is there a way out to stop the loop?

sometimes i use debug code to alert something in javascript (for example, matching something in regular expression), but forget a modifier and and the alert is in an infinite loop (or if the loop matches the pattern 300 times). If using Firefox, the alert keeps on coming out, and there is no way to even close the tab, the window, or the app.

If I force exit, it will close all the tabs and even other windows of Firefox... is there actually a way to stop the loop more gracefully?

like image 864
nonopolarity Avatar asked May 21 '09 19:05

nonopolarity


People also ask

How do you stop an infinite loop in JavaScript?

An infinite loop will run forever, but the program can be terminated with the break keyword. In the below example, we will add an if statement to the while loop, and when that condition is met, we will terminate the loop with break .

What will happen if while loop runs indefinitely in JavaScript?

An infinite loop is a piece of code that keeps running forever as the terminating condition is never reached. An infinite loop can crash your program or browser and freeze your computer. To avoid such incidents it is important to be aware of infinite loops so that we can avoid them.

What causes an infinite loop in JavaScript?

An infinite loop is a condition where a piece of your JavaScript code runs forever caused by a fault in your code that prevents the loop from getting terminated.

How do you stop an infinite loop?

You can press Ctrl + C .


1 Answers

The short answer is: No.

This is one good reason to use Firebug and the console.log function. Which, ironically, will cause the "stop script because it's running away dialog" to not display in some cases, meaning you are right back where you are now.

Chrome and Opera have this feature. IE doesn't, Apple Safari doesn't either.

Not a native solution but you could try this grease-monkey script: http://www.tumuski.com/2008/05/javascript-alert-cancel-button/

Also, you could simply override the alert function to use a confirm dialog instead and stop showing alerts if the confirm is canceled:

var displayAlerts = true;

And then:

function alert(msg) {
  if (displayAlerts) {
     if (!confirm(msg)) {
       displayAlerts = false;           
     }
  }
}
like image 198
cgp Avatar answered Sep 28 '22 00:09

cgp