Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug javascript when it goes into infinite loops and recursive calls in Javascript?

When you are in the infinite loop or recursive calls, basically the browser stops responding to anything (either on Chrome or FF). You cannot see logs, cannot get into debugger, even you cannot open the console itself. The browser just simply freezes. This is so annoying. It seems I can do nothing but sitting here scratching my head... Anyone can shed light on how to solve this?

like image 716
lkahtz Avatar asked Oct 10 '12 09:10

lkahtz


People also ask

How do you stop an infinite loop in JavaScript?

pause script with F8, Ctrl+\ or by clicking Pause script execution button, press mouse button for 1-3 seconds on the button again to see more options, move click action to square stop button on expanded menu to stop permanently script execution.

Why is JavaScript so hard to debug?

What makes JavaScript great is also what makes it frustrating to debug. Its asynchronous nature makes it easy to manipulate the DOM in response to user events, but it also makes it difficult to locate problems.


Video Answer


1 Answers

Another trick you could try is to have the Web developer tools in Chrome open and try to hit Pause when the Browser apparently hangs. Then it should break at the line where it's currently executing. With some stepping out you should get to the bottom of this.

Assuming you know (or suspect) the function where the infite loop happens you could add code like this:

var calls = 0; function iSuspectToBeLoopingInfititely() {   calls += 1;   if (calls > 100) { debugger; } } 

This will stop the JavaScript debugger in Chrome once the method has been called 100 times. Note: Chrome will only break for debugger; calls if you actually have the Developer Tools window open.

like image 166
Tigraine Avatar answered Oct 22 '22 19:10

Tigraine