> For the complete documentation index, see [llms.txt](https://codehs.gitbook.io/introcs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://codehs.gitbook.io/introcs/animation-and-games/using-timers.md).

# 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."

```
/**
 * The Random Circles Program
 */

var MAX_RADIUS = 100;
var MAX_CIRCLES = 1000;
var counter = 0;

function start(){
    setTimer(draw, 50);
}

function draw(){
    drawCircle(Randomizer.nextInt(0, MAX_RADIUS),
               Randomizer.nextColor(),
               Randomizer.nextInt(0, getWidth()),
               Randomizer.nextInt(0, getHeight()));

    counter++;

    if(counter == MAX_CIRCLES){
        stopTimer(draw);
    }
}

function drawCircle(radius, color, x, y){
    var circle = new Circle(radius);
    circle.setColor(color);
    circle.setPosition(x, y);
    add(circle);
}
```

![Using Timers](https://2758402946-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4CE_DmHLmpU7V-mTCM%2F-M4CE_o17xJUBglR8D4N%2F-M4CEi11th9VJgwy0yEv%2Fanimation_timers_randomcircle.png?generation=1586138908668534\&alt=media)

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:

```
startTimer(giveTreat, 1000);
```

Karel could then stop the timer by issuing the following command:

```
stopTimer(giveTreat);
```

## 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:

```
startTimer(giveTreat, giveToy, takeKarelForWalk, 1000);
```

Instead of passing multiple functions when calling `startTimer`, Karel will need to create one function that then makes calls to the other functions:

```
startTimer(makeKarelHappy, 1000);

...

function makeKarelHappy(){
    giveTreat();
    giveToy();
    takeKarelForWalk();
}
```

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`.
