What is setTimeout and setInterval in JavaScript?

In JavaScript, setTimeout and setInterval are two powerful functions used to handle timing events in your code.

setTimeout allows you to execute a function after a specified delay (in milliseconds). This can be useful for creating delays in your code.

setInterval, on the other hand, repeatedly executes a function at specified intervals (also in milliseconds) until it is stopped.

Here are examples of both functions:

// Using setTimeout setTimeout(function() { console.log('This message appears after 2 seconds'); }, 2000); // Using setInterval let count = 0; const intervalId = setInterval(function() { console.log('This message appears every 1 second'); count++; if (count === 5) { clearInterval(intervalId); // Stops the interval after 5 messages } }, 1000);

setTimeout setInterval JavaScript timing functions execute function after delay repeat function at intervals