Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you debug JavaScript which hangs the browser?

I'm working on a substantially large rich web page JavaScript application. For some reason a recent change is causing it to randomly hang the browser.

How can I narrow down where the problem is? Since the browser becomes unresponsive, I don't see any errors and can't Break on next using FireBug.

like image 809
JeanPaul Avatar asked Sep 02 '11 22:09

JeanPaul


People also ask

Can we debug JavaScript?

But fortunately, all modern browsers have a built-in JavaScript debugger. Built-in debuggers can be turned on and off, forcing errors to be reported to the user. With a debugger, you can also set breakpoints (places where code execution can be stopped), and examine variables while the code is executing.


2 Answers

Instead of commenting the hell out of your code, you should use a debug console log.

You should use the console.log() functionality provided by most modern browsers, or emulate it if you use a browser that doesn't support it.

Every time you call console.log('sometext'), a log entry in the debug console of your browser will be created with your specified text, usually followed by the actual time.

You should set a log entry before every critical part of your application flow, then more and more until you find down what log isn't being called. That means the code before that log is hanging the browser.

You can also write your own personal log function with added functionalities, for example the state of some particular variable, or an object containing a more detailed aspect of your program flow, etc.

Example

console.log('step 1');  while(1) {}  console.log('step 2'); 

The infinite loop will halt the program, but you will still be able to see the console log with the program flow recorded until before the program halted.

So in this example you won't see "step 2" in the console log, but you will see "step 1". This means the program halted between step 1 and step 2.

You can then add additional console log in the code between the two steps to search deeply for the problem, until you find it.

like image 148
Jose Faeti Avatar answered Oct 05 '22 03:10

Jose Faeti


You can add debugger; anywhere in your JS code to set a breakpoint manually. It will pause execution and allow you to resume/inspect the code (Firebug/FF).

Firebug Wiki page: http://getfirebug.com/wiki/index.php/Debugger;_keyword

like image 30
Ricardo Tomasi Avatar answered Oct 05 '22 04:10

Ricardo Tomasi