Timer Functions
Timer functions run code later or again and again.
They help with delays, clocks, and repeating actions.
Think of an oven timer or a metronome.
setTimeout
clearTimeout
setInterval
clearInterval
Delay units
setTimeout
This runs a function once after a wait.
The wait is measured in milliseconds.
1000 milliseconds is one second.
clearTimeout
setTimeout returns an id.
Pass that id to clearTimeout to cancel the wait.
setInterval
This runs a function again and again on a schedule.
Great for clocks and repeating game ticks.
clearInterval
Always stop intervals you no longer need with clearInterval.
Forgotten intervals keep running like a drip.
Arrow callbacks
You can pass arrow functions too.
Not exact clocks
Timers aim for the delay you ask for.
The browser may wait a little longer if it is busy.
Tip: Save the timer id. If you start an interval, plan how and when you will clear it.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.