JavaScript Timing Functions

The setTimeout function takes a function and an integer. The function will run after the given number of milliseconds. You can stop a timeout by with clearTimeout.

The setInterval function takes a function and an integer. The function will run every given number of milliseconds.

Interestingly, every time you run the code, you create a new interval in addition to the old ones. You'll have to reload this page to halt them.

You can stop intervals with clearInterval. setInterval is not accurate, however. setInterval will pause If anything blocks the main thread so is not appropriate to use as a clock. Use setTimeout repeatedly and correct for clock drift each time. requestAnimationFrame is used for browser animations. It's frequency should match your display's refresh rate. requestAnimationFrame should pause when the animation is hidden. cancelAnimationFrame can stop an animation.