79. What are setTimeout and setInterval timing functions in JavaScript?
easy

setTimeout() and setInterval() are two timing functions available in JavaScript that allow you to specify a function that should be called after a certain amount of time has passed. These functions are useful for measuring the time it takes for your code to execute, or for performing tasks at regular intervals.


Here's an example of how to use setTimeout() and setInterval():

// Execute 'console.log("Hello")' after 1 second
setTimeout(() => {
  console.log("Hello");
}, 1000);

// Execute 'console.log("World")' every 500 milliseconds (or 0.5 seconds)
const interval = setInterval(() => {
  console.log("World");
}, 500);

In this example, we are using setTimeout() to execute the function console.log("Hello") after 1 second, and we are using setInterval() to execute the function console.log("World") every 500 milliseconds (or 0.5 seconds).

To stop the execution of a setTimeout() or setInterval() call, you can use the clearTimeout() function:

// Stop the 'hello' timeout after 2 seconds
const timeoutId = setTimeout(() => {
  console.log("Hello");
}, 1000);

setTimeout(() => {
  clearTimeout(timeoutId); // Clear the timeout
  console.log("Stopped");
}, 2000);

In this example, we are using clearTimeout() to stop the execution of a setTimeout() call that logs "Hello" after 1 second. We are storing the ID returned by setTimeout() in a variable called timeoutId, which we can use later to clear the timeout by calling clearTimeout(timeoutId).


Similarly, you can stop an setInterval() call by using the clearInterval() function:

// Stop the 'world' interval after 5 seconds
const intervalId = setInterval(() => {
  console.log("World");
}, 1000);

setTimeout(() => {
  clearInterval(intervalId); // Clear the interval
  console.log("Stopped");
}, 5000);

In this example, we are using clearInterval() to stop an setInterval() call that logs "World" every second. We are storing the ID returned by setInterval() in a variable called intervalId, which we can use later to clear the interval by calling clearInterval(intervalId).