Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Debug Memory Leaks, Infinite Loops, and Executing Javascript in the Browser?

What are the recommended ways to check for infinite loops in javascript in the browser? Say I open Chrome and it crashes, is there a way to breakpoint or somehow pinpoint where that occurred?

Then I'm wondering, how do I see a running list of the executing scripts in the browser (say some timer I lost track of is running and it's slowing things down)? Preferably in Chrome/Safari, but Firefox would work too.

I use the element inspector/console all the time, I just haven't figured out ways to effectively debug these 3 things.

Thanks!

like image 354
Lance Avatar asked Feb 23 '11 17:02

Lance


People also ask

How do you debug an infinite loop?

The best first step for debugging an infinite loop is to comment out different sections or lines of code, then running the program to see where the infinite loop is occurring. Start by testing any sections that contain for or while loops, then if/else statements, then other blocks of code.

How do you run an infinite loop in JavaScript?

In for() loop: To avoid ending up in an infinite loop while using a for statement, ensure that the statements in the for() block never change the value of the loop counter variable. If they do, then your loop may either terminate prematurely or it may end up in an infinite loop.


1 Answers

1. Memory leaks

  • Microsoft JavaScript Memory Leak Detector (IE)
  • Drip (IE)
  • Leak monitor (FF)

2. Inifinite loops

I don't exactly understand what the browser could point you to in the case of complex infinite loop spreading across hundreds of functions. Sure, I'd love the browser to pinpoint simple loops like some function not returning for 15 seconds. But at least we have something, browser tells you a) that script is running slow, and b) what functions were called and how much time each one took. Also, you can set a breakpoint and watch it run step by step.

3. Monitoring timers and intervals

Open WebKit's timeline panel, hit "Record" and monitor everything you might want to know about each timer and interval. If you're not using WebKit you can code something simple yourself:

_setTimeout = setTimeout
setTimeout = function(fn, time) {
  var timeout = _setTimeout(function() {
    console.log('Timeout #' + timeout + ' fired on ' + (fn.name || 'anonymous'))
    fn()
  }, time)
  return timeout
}

Usually I simply make document.title blink when timeout/interval fires.

4. General code performance

  • Speed Tracer for Google Chrome
  • Firebug Paint Events for Firefox
  • Javascript Performance Monitor - a little infobox that will help you monitor FPS and memory allocation
like image 144
Alexey Lebedev Avatar answered Sep 17 '22 15:09

Alexey Lebedev