JavaScript set Interval

In JavaScript, setInterval() is a method used to repeatedly execute a function or a piece of code at a specified time interval. It takes two parameters: the function to be executed and the time delay (in milliseconds) between each execution.

Here’s an example that demonstrates the usage of setInterval():

// Define a function to be executed
function greet() {
  console.log("Hello!");
}

// Call setInterval and pass the function and time delay
var intervalId = setInterval(greet, 1000); // Executes the function every 1000 milliseconds (1 second)

In this example, the greet() function will be executed every 1000 milliseconds (1 second). The setInterval() function returns an interval ID that can be used to later stop the execution using the clearInterval() method.

Here’s an example that shows how to stop the execution using clearInterval():

// Define a function to be executed
function greet() {
  console.log("Hello!");
}

// Call setInterval and store the interval ID
var intervalId = setInterval(greet, 1000); // Executes the function every 1000 milliseconds (1 second)

// Stop the execution after 5 seconds (5000 milliseconds)
setTimeout(function() {
  clearInterval(intervalId);
}, 5000);

In this updated example, the setInterval() function is called to execute the greet() function every second. However, after 5 seconds (5000 milliseconds), the clearInterval() function is called with the interval ID to stop the execution.

Remember to use clearInterval() to stop the interval when you no longer need it, as failing to do so may lead to unnecessary resource consumption and unwanted behavior in your code.