Sunday, December 3, 2006

JavaScript Debug Log

Date: Monday, 18 Dec 2006 14:08

Even with the most advanced debugging tools, every program requires a little "printf debugging": run your program, print out state as it executes, and visually verify that everything is working properly. Unfortunately, there is no built in console to print debug messages to in JavaScript, forcing many JavaScript programmers to revert to calling alert() in their code. alert is completely infeasible for a function that gets called a lot, as it halts execution until you click an OK button. This recipe creates a simple debug log window that does not halt execution:

function log(message) {
if (!log.window_ log.window_.closed) {
var win ="", null, "width=400,height=200," +
"scrollbars=yes,resizable=yes,status=no," +
if (!win) return;
var doc = win.document;
doc.write("<html><head><title>Debug Log</title></head>" +
log.window_ = win;
var logLine = log.window_.document.createElement("div");

To print log messages, you just call log() within your code:

for (var i = 0; i < 10; i++) {
log("This is log message #" + i);

When you push your code to production, you can just replace the definition of log with an empty function so your users will not see your debug messages.

See the example

1 comment:

Marvelan said...

Nice blog its a good informative blog about java script. Java Server Pages, which is enhanced known as JSP, is an additional open-source programming language that can be consummate without even knowing Java Script. Tag extensions that are used in this web application development language, are straightforward and spotless in form.
Thanks for this nice sharing.