Using Timers
Using Timers
Timers are a key part of creating animations. As such, they are often used to create fun and interesting graphical programs. Let's take a look at one such program, called "Random Circles."
Let's start by examining the timer. The timer is created at the very beginning of the program in the start
function.
Stopping a Timer
Timers will continue to run until they are given the command to stop. A timer can be stopped by issuing the stopTimer(functionName)
command. The functionName
should be the name of the function that was originally passed to the timer when creating it with startTimer()
.
For example, Karel could create a timer that called a giveTreat
function every 1000 milliseconds:
Karel could then stop the timer by issuing the following command:
Using Multiple Functions with a Timer
Programs often need to call multiple functions every tick of the timer. However, the call to startTimer
can only take one single function. This code would not work for Karel:
Instead of passing multiple functions when calling startTimer
, Karel will need to create one function that then makes calls to the other functions:
With this code, the makeKarelHappy
function will be called every 1000 milliseconds. That function then calls each of Karel's other functions. Notice that in the Random Circles program, the timer calls the draw
function, which then calls drawCircle
.
Last updated
Was this helpful?