Using setTimeout() and clearTimeout() to Animate a Page
The code described above makes a div
jump across the screen. If you want the div
to drift more slowly across the screen or to move along a specific path, you can use timing loops (discussed in Chapter 9) to animate your div
.
To make a div
move smoothly across the screen, write a function that moves the div
a little bit, then uses setTimeout()
to call itself in a few milliseconds. Figure 13-10 contains code that causes an image of the number 1 to roam randomly around the screen.
Figure 13-10. The Wandering One
Line-by-Line Analysis of Figure 13-10
In Figure 13-10, the image of the number 1 starts ...
Get The Book of JavaScript, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.