Small Steps II — Making Things

Running a function when it is time

Run a function when it is time.

What you will learn

An event is something a program responds to. A callback is a function entrusted to run when that event occurs. Use Timer to run a function about once a second.

Try it

Example · example1.cpp
int ticks = 0;

void on_timer()
{
    ticks = ticks + 1;
    print("Tick ", ticks);
}

void small_main()
{
    Timer timer;

    timer.start(1.0, on_timer);
    sleep(3.2);
    timer.stop();
}

on_timer has no () in start(1.0, on_timer) because you are specifying the function to call later, rather than calling it now.

ticks, outside all functions, is a global variable shared by several functions. Each callback adds 1. Timer events are processed during sleep too; stop stops the timer. Scheduling does not guarantee an exact number of calls.

Exercise

Make a callback run every 0.5 seconds, increasing count by 1 and printing it. Call stop on the Timer after about 2.2 seconds.

Exercise starter · exercise1_starter.cpp
int count = 0;

void on_timer()
{
    // Increase and print count.
}

void small_main()
{
    Timer timer;

    // start the timer, wait about 2.2 seconds, then stop it.
}

Hint

Use timer.start(0.5, on_timer) and increase count in the callback.

show solution
int count = 0;

void on_timer()
{
    count = count + 1;
    print("Count: ", count);
}

void small_main()
{
    Timer timer;
    timer.start(0.5, on_timer);

    sleep(2.2);

    timer.stop();
}
← Previous lessonNext lesson →