SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 191 | Next

Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb

"Accelerated DOM Scripting with Ajax, APIs, and Libraries"


Figure 6-2. Changing the value over time
To do this, you need to use either setInterval() or setTimeout(). What??™s the difference?
Both take two parameters: the first is the code to execute, and the second is the amount of
time in milliseconds to wait before being called. Both return an ID that can be used to cancel
the call whenever you want:
var intervalID = setInterval(performAnimation, 1000); // call function every 1000 ms
var timeoutID = setTimeout(performAnimation, 1000); // call function in 1000 ms
CHAPTER 6 n VISUAL EFFECTS 132
You can also pass in a string to be evaluated, which can be handy to pass in variables (I
prefer the previous approach, though):
var intervalID = setInterval("performAnimation("+id+")", 1000);
var timeoutID = setTimeout("performAnimation("+id+")", 1000);
The difference between setInterval() and setTimeout() is that setTimeout() will execute
the code only once, whereas setInterval() will continue to execute the code every second (or
whatever interval you set) until the call is cancelled.
To prevent setInterval() from firing, just call clearInterval() with the ID that was
returned when you called the setInterval() function:
clearInterval(intervalID);
Likewise, to stop the setTimeout() call from firing, just call clearTimeout() with the ID
that was returned from the setTimeout() function. Trying to clear a timeout after it has fired or
with an invalid ID doesn??™t do anything, so you don??™t have to worry about JavaScript errors.


Pages:
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203