Timers (forever
!)
Goals:
- Use the Pencil Code
forever
function to set up Timing events - Transition from queue-based to frame-based animation
Coding Snippets:
forever
sets up a recurring timer that by default executes a callback 30 times per second. Set the timer to fire more or less frequently by specifying the optional first argument.forever
returns a unique id for each timer- Remove a timer from within its callback by calling
stop()
. Outside of its own callback, remove a timer by passing its ID as the argument tostop
.
Math and Computer Concepts:
forever
is a Pencil Code function that facilitates executing a callback repeatedly at fixed intervals. It is an alternative to setting up a timing event using the built-in JavaScript functionsetInterval
.- Remove a timer created with
forever
using thestop
method. From within a timer's callback,stop()
(with no arguments) references that timer. Outside of the callback,stop()
removes all timers.stop(x)
removes a timer with an ID referenced byx
.
- When working with forever loops, it is often advantageous to work with frame-based animation. Call
speed Infinity
at the beginning of your script, and no longer worry about animation queues! The tradeoff is that you have to code the animation logic yourself.
Activities:
Save each of the following in a folder called Forever.
- PermaPerfectFit: place calls to
sizexy
inside the callback toforever
, and use these values to constantly display a circle that always fits inside the window perfectly (i.e., centered at the origin with diameter equal to the smaller of the page width or height). - ConfettiCount: use
forever
to perpetually draw dots on the screen in random positions. Use a label to display the number of dots, updating it using techniques described in Label Recycling! - Code a new RandomTurtles program that uses frame-based animation and timers so that it repeats indefinitely. As an added challenge, avoid explicit use of
for
loops; rather, usehatch
to create your sprites and theeach
method to iterate over that collection. Code a program that displays two different AnalogClocks, displayed side-by-side. They should both have second hands that move in discrete units (i.e., ticking away once per second). For the first clock, set the time initially with a call to
Date
, then update it using a timer that fires once per second. For the second clock, use a timer that fires more frequently, and re-set the clock each time based on a new call toDate
. (Why is the second version the better approach?)