What are JavaScript timers

JavaScript provides two main built-in functions for creating timers: setTimeout() and setInterval().

setTimeout()

The setTimeout() function is used to execute a function after a specified number of milliseconds.

Example:

setTimeout(() => { console.log('This message is displayed after 2 seconds'); }, 2000);

setInterval()

The setInterval() function is used to repeatedly execute a function at specified intervals.

Example:

let intervalId = setInterval(() => { console.log('This message is displayed every 1 second'); }, 1000); // To stop the interval after 5 seconds setTimeout(() => { clearInterval(intervalId); console.log('Interval cleared'); }, 5000);

JavaScript timers setTimeout setInterval clearTimeout clearInterval asynchronous JavaScript