Timers

Allows JavaScript to be run at specified times.

 

setTimeout()

Runs once.

Requires:

  • Name of function to run
  • Duration in milliseconds

An alert is shown after 3 seconds:

 

setInterval()

Repeats specified function at the specified interval duration.

Requires:

  • Name of function to run
  • Duration in milliseconds

Initial image is shown, and then changed to the next array index value every 3 seconds:

 

 

clearTimeout() and clearInterval() are the complementary functions of the above setTimeout() and setInterval() functions, that allow us to clear the previously set timers.

 

For example, setInterval() also returns a value which we can store in a variable, which we can then use within the clearInterval() function. This example uses the onclick event to clear the setInterval timer and hence stop the images changing:

Leave a Reply