Change Background Color Every Second in JavaScript?

To change the background color of an element every second in JavaScript, you can use the setInterval() method. The setInterval() method allows you to call a given function again and again after a given period of time(in milliseconds).

The setInterval() method needs two parameters. First, the name of the function that is to be called repeatedly, and second, the time in milliseconds after which the given function will be called.

Here is its syntax:

setInterval(function_name, milliseconds);

Now, to set the background color of the element dynamically, you can use the backgroundColor property.

The following example changes the background color of the body element after every second:

Example:

let i = 0;
let colors = ['yellow','blue', 'red', 'orange'];

// Triggers every second
function changeColor(){
    document.body.style.backgroundColor = colors[i];
    i++;
    if(i>=colors.length){
        i=0;  // Reset i to 0 if it exceeds colors length
    }
}

setInterval(changeColor, 1000);

Change Background Color Every Second Randomly

In the above example, the colors array is fixed. This means it will keep on repeating the same 4 colors again and again. However, we can extend this functionality to higher levels such as changing the background color dynamically.

To generate random colors we will use the Math.random() function.

As maximum possible HEX number is fff whose decimal equivalent is 16777215. So, we will be generating numbers from 0 to 16777215 randomly after every second and then converting this randomly generated decimal number to its equivalent HEX using the toString(16) method.

Here is the full JavaScript code with a live example:

Example:

// Triggers every second
function changeColor(){
    let randomColor = Math.floor(Math.random()*16777215).toString(16);
    document.body.style.backgroundColor = '#'+randomColor;
}

setInterval(changeColor, 1000);

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.