Timers

Objectives

  • Use the setInterval function
  • Use the setTimeout function
  • Clear a timer set by setInterval

Using timers

  • setTimeout(func, n): used to run function func in x milliseconds; it returns a reference to the timer which can be passed to clearTimeout to stop the timer
  • clearTimeout(timer): clears the specified timeout timer
  • setInterval(func, n): used to run function func every x milliseconds; it returns a reference to the timer which can be passed to clearInterval to stop the timer
  • clearInterval(timer): clears the specified interval timer
  • Example of using setTimeout to trigger a function in one second: setTimeout(trouble, 1000);
  • Example of using setInterval to trigger a function every second: setInterval(trouble, 1000);

Example of setTimeout, setInterval, clearInterval

See more sophistcated versions at date4.html and date8.html.

Code for example