How to usesetInterval() Method in Javascript

We can use the setInterval() method to repeatedly toggle the background color of an element. The setInterval() method executes a given function at specified intervals (in milliseconds).

Syntax:

window.setInterval(function, milliseconds);

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Blinking Background Color
    </title>
</head>
  
<body>
    <!-- The div that will have the 
        blinking background -->
    <div id="blinkDiv" style="width: 400px; 
                height: 100px; 
                padding: 20px; 
                text-align: center; 
                font-size: 24px;">
                  
        <!-- Content inside the div -->
        <h1 style="color: green;">
            w3wiki
        </h1>
    </div>
  
    <script>
  
        // Get the div element by its ID
        const blinkDiv =
            document.getElementById('blinkDiv');
  
        // An array of colors to be used for blinking
        const colors = ['#ff0000', 'black', '#0000ff'];
  
        // Variable to keep track of the
        // current color index
        let currentColorIndex = 0;
  
        // Function to toggle the background
        // color of the div
        function blinkBackground() {
            blinkDiv.style.backgroundColor =
                colors[currentColorIndex];
            currentColorIndex =
                (currentColorIndex + 1) % colors.length;
        }
  
        // Start the blinking by setting an interval 
        // that calls the blinkBackground 
        // function every 1000ms (1 second)
        const blinkingInterval =
            setInterval(blinkBackground, 1000);
  
        // To stop blinking after 5 seconds, 
        // use setTimeout to clear the interval
        setTimeout(() => {
            clearInterval(blinkingInterval);
        }, 5000);
    </script>
</body>
  
</html>


Output:

How to Add Blinking Background Color in JavaScript ?

In this article, we will learn how to create a blinking background color. Adding a blinking background color to an element can be an attention-grabbing visual effect that can be useful in various web applications. It can be achieved using JavaScript by toggling the background color of an element between two or more colors at regular intervals.

Below are the approaches through which we can do this:

  • Using setInterval() Method
  • Using CSS Animations and JavaScript

Similar Reads

Approach 1: Using setInterval() Method

We can use the setInterval() method to repeatedly toggle the background color of an element. The setInterval() method executes a given function at specified intervals (in milliseconds)....

Approach 2: Using CSS Animations

...