JavaScript Timing Events


Timing events are used in JavaScript to run code at predetermined intervals or when a predetermined amount of time has elapsed. JavaScript supports two different timing events: setTimeout() and setInterval().

setTimeout()

The setTimeout() method is used to execute a piece of code after a specified delay (in milliseconds). The method takes two arguments: the code to be executed (as a function or string), and the delay (in milliseconds).

Example

Preview

setInterval()

The setInterval() method is used to execute a piece of code repeatedly at a specified interval (in milliseconds). The method takes two arguments: the code to be executed (as a function or string), and the interval (in milliseconds).

Example

Preview

To end a timer started using setTimeout() or setInterval(), use the clearTimeout() or clearInterval() methods, respectively. The ID of the timer to be stopped, returned by calls to setTimeout() or setInterval(), is the only parameter to these methods.

Timing events can be helpful for many things, such as adding animations, checking for changes, and periodically refreshing content. Timing events can suck up system resources and affect the speed of your application, so it's important to use them sparingly.