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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With