Set Interval in JavaScript

In this article, I will guide you on how to Set Interval in Javascript.

So, let's get started,

What is a Set Interval?

In JavaScript, set Interval is a built-in function that is used to repeatedly execute a specific function or a block of code at specified time intervals. It's like setting a timer to perform a task repeatedly at regular intervals. Here's the basic syntax

setInterval(function, milliseconds);
  • function: The function you want to execute repeatedly.
  • milliseconds: The time interval, in milliseconds, after which the function will be called again.

Let’s Understand With Example

Certainly! Let's consider a real-life example involving a traffic light. setInterval can be used to simulate the changing of traffic lights at regular intervals.

let currentLight = "red"; // Initially, the traffic light is red

function changeTrafficLight() {
  if (currentLight === "red") {
    // Change from red to green
    currentLight = "green";
    console.log("Traffic light is now green. Go!");
  } else if (currentLight === "green") {
    // Change from green to yellow
    currentLight = "yellow";
    console.log("Traffic light is now yellow. Prepare to stop.");
  } else {
    // Change from yellow to red
    currentLight = "red";
    console.log("Traffic light is now red. Stop!");
  }
}

setInterval(changeTrafficLight, 5000); 
// Change the traffic light every 5 seconds (5000 milliseconds);
  • We start with a currentLight variable set to "red," indicating that the traffic light is initiallyred.
  • The changeTrafficLight function is defined tochange the traffic light from red to green, thento yellow, and back to red, simulating a trafficlight cycle.
  • We use setInterval to call thechangeTrafficLight function every 5 seconds(5000 milliseconds), mimicking the timing of the traffic light cycle.

So, this code simulates a traffic light changing its signal from red to green, then to yellow, and back to red at regular 5-second intervals, just like a real traffic light would cycle through its colors.

Summary

In this article, I have tried to cover Set Interval in Javascript.