Time

Usually we think about programs as something recipes that execute sequentially. However, sometimes we wish to wait or repeat something at different times.

Timeout

The setTimeout function lets us schedule something to be executed at a later time.

Imagine you were responsible for the launch of SpaceX Falcon 9 rocket. Your program has to call the liftOff function exactly on the 1 minute mark.

setTimeout(() => {
    liftOff();
}, 60000);

The first argument to setTimeout is the function that is to be executed, the second argument is when that function should be executed. Notice that the last argument is provided as milliseconds.

Interval

The setInterval function allows you to do something at a repeated interval.

Note that the function you schedule is not executed immediately, but executed at the first interval.

setInterval(() => {
    measureTemperature();
}, 60000);

Last updated