Two small but useful javascript facts
Passing parameters into setTimeout callbacks
setTimeout (and setInterval too perhaps?) accepts a third parameter, an array of parameters to pass in to your callback function, so
setTimeout(function() {
myFunction(need, to, pass, these, in);
}, 200);
Can far more efficiently be written
setTimeout(myFunction, 200, [need,to,pass,these,in]);
Firebug’s console still works when you’re at a breakpoint (and can be very useful for debugging jQuery)
When debugging using firebugĀ and you set a breakpoint, when your code stops at that breakpoint
- you can still use firebug’s console to run any code you like
- “this” in firebug’s console is always set to what “this” is set to in your code
This means that you can play around with your variables at will at any given point in your code. It may be that I was a dunce for not knowing this, but I’ve never seen anybody I work with take advantage of these facts, so maybe it’s news to more people than just me…. and it’s bloody useful so I feel no shame in shouting about it.
For instance jQuery, for all its benefits, can be a pain to debug due to the fact that so much work is done by a single string (your selector) and on a single line of code (using chaining), and that jQuery often doesn’t give very helpful error messages. This means if you wnat to debug a certain line you have to either a) keep stepping in and out of the murky world of jQuery’s inner methods in order to find out where and why the unexpected bug is happening; or b) add temporary lines to your code which carry out only part of the single jQuery line, then reload the page to observe if they succeed or fail.
Not so if you set a breakpoint and then use the console. For instance, say a fairly complex line of jQuery misfires.
$(">p input:focus", myContainer).css("height", adjustHeight).children(".shrinker").remove().end().wrapAll("<div class=\"done\">");
By setting a breakpoint in my code on this line, and then copying the line into the console and running it, I can progressively remove/tweak bits until the error no longer appears; I never have to step through jQuery’s code and I never have to reload the page. Easy peasy.
No related posts.