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 = window.open("", null, "width=400,height=200," +
"scrollbars=yes,resizable=yes,status=no," +
"location=no,menubar=no,toolbar=no");
if (!win) return;
var doc = win.document;
doc.write("<html><head><title>Debug Log</title></head>" +
"<body></body></html>");
doc.close();
log.window_ = win;
}
var logLine = log.window_.document.createElement("div");
logLine.appendChild(log.window_.document.createTextNode(message));
log.window_.document.body.appendChild(logLine);
}
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.
1 comment:
Hello,
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.
Pamela
Post a Comment