Lecture 17: The Document Object Model (DOM); Events and Timers
Reading: 8.2; 9.2; 11.1
Except where otherwise noted, the contents of this document are
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst.
All rights reserved.
Any redistribution, reproduction, transmission, or storage of part
or all of the contents in any form is prohibited without the author's
expressed written permission.
8.2.6: Debugging Common Errors
8.1: Key JavaScript Concepts
8.2: JavaScript Syntax
8.3: Program Logic
8.4: Advanced JavaScript Syntax
Debugging JS code in Firebug
Firebug/Chrome JS debugger can set breakpoints, step through code, examine values (Script tab)
interactive console for typing in arbitrary JS expressions (Console tab)
JSLint
JSLint: an analyzer that checks your JS code, much like a compiler, and points out common errors
function delayMsg() {
setTimeout(booyah, 5000);
document.getElementById("output").innerHTML = "Wait for it...";
}
function booyah() { // called when the timer goes off
document.getElementById("output").innerHTML = "BOOYAH!";
}
setInterval example
var timer = null;// stores ID of interval timer
function delayMsg2() {
if (timer == null) {
timer = setInterval(rudy, 1000);
} else {
clearInterval(timer);
timer = null;
}
}
function rudy() { // called each time the timer goes off
document.getElementById("output").innerHTML += " Rudy!";
}
Passing parameters to timers
function delayedMultiply() {
// 6 and 7 are passed to multiply when timer goes off
setTimeout(multiply, 2000, 6, 7);
}
function multiply(a, b) {
alert(a * b);
}
any parameters after the delay are eventually passed to the timer function
doesn't work in IE6; must create an intermediate function to pass the parameters
why not just write this?
setTimeout(multiply(6 * 7), 2000);
Common timer errors
many students mistakenly write () when passing the function