Creating a unique JavaScript script that gradually adjusts the background color using the setTimeout() function

Is there a way to create a function that continuously changes the background color every 15 seconds by picking colors from an array that starts over once all colors have been used, without having the function run just one time?

$(document).ready(() => {
    const colors = ['#83ACDE','#EDCA38','#A1B2C3','#3C2B1A'];
    let index = 0;
    
    setInterval(() => {
        $('body').css("backgroundColor", colors[index]);
        index = (index + 1) % colors.length;
    }, 15000);
});

Answer №1

Consider implementing CSS animations for a quicker and more efficient solution.

body {
  background-color: #83ACDE;
  animation: changeBackgroundColor 60s infinite;
}

@keyframes changeBackgroundColor {
  0%,
  24.99%,
  100% {
    background-color: #83ACDE;
  }
  25%,
  49.99% {
    background-color: #EDCA38;
  }
  50%,
  74.99% {
    background-color: #A1B2C3;
  }
  75%,
  99.99% {
    background-color: #3C2B1A;
  }
}

Answer №2

To properly handle the exceeding of the array length, make sure to "reset" your i variable as needed...

const colors = ['#83ACDE','#EDCA38','#A1B2C3','#3C2B1A'];
$(function() { start(0); });
function start(i){
  setTimeout(function(){
    $('body').css("backgroundColor", colors[i]);
    i++;
    if (i >= colors.length) {
      i = 0;
    }
    start(i);
  }, 2000); // Adjusted to 2 seconds for illustration
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Hello World</div>

Answer №3

One suggestion I have is to simply reset i, but another option is to utilize the modulus operator %. Here's an example:

const colors = ['#CFAA65', '#92D865', '#6A85B4', '#E1A383'];

function initialize(i) {
  setTimeout(function() {
    $('body').css("backgroundColor", colors[i]);
    i++;
    initialize(i % colors.length);
  }, 500); 
}
initialize(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Demo</div>

Answer №4

A more efficient approach is to utilize the modulus (remainder) operator in conjunction with the array length, like this:

start ((i + 1) % colors.length);

By using this method, the incrementation resets back to 0 when i + 1 equals colors.length.

const colors = ['#83ACDE','#EDCA38','#A1B2C3','#3C2B1A'];
function start(i){
  setTimeout(function(){
    $('body').css("backgroundColor", colors[i]);
    start((i + 1) % colors.length);
  }, 1000); // Set at 1 second for better visibility
}
start(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

It's worth noting that the conditional if statement testing for a valid index has been removed, as it is no longer required.

Answer №5

Initialize i to 0 whenever the total number of elements in the array colors is reached:

function begin(i){
  if(i < colors.length){
    setTimeout(function(){
      $('body').css("backgroundColor", colors[i]);
      i++;
      if(i == colors.length) { i=0; }
      begin(i);
    }, 15000);
  }
}

Answer №6

Just a slight tweak in your code and it will be perfect.

const shades = ['#83ACDE','#EDCA38','#A1B2C3','#3C2B1A'];
const shadeCount = shades.length;
$(document).ready(() => {   run(0);});
 function run(i){
 setTimeout(function(){
  $('body').css("backgroundColor", shades[i]);
 i++;
 if (i >= shadeCount) {
  i = 0;
 }
 run(i);
}, 1000); 
}

Answer №7

The problem lies within your code due to the if statement terminating the loop when the value of i exceeds the range of the colors array.

To resolve this issue, you can utilize the modulo operator to divide the value of i by the length of the array and use the remainder as the index. Additionally, you can streamline the logic by immediately setting the initial background color. Here is a revised version:

$(document).ready(() => {
  const colors = ['#83ACDE', '#EDCA38', '#A1B2C3', '#3C2B1A'];

  function start(i) {
    $('body').css("backgroundColor", colors[i++ % colors.length]);
    setTimeout(function() { start(i); }, 1000);
  }

  start(0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №8

$(document).ready(() => {
const shades = ['#DE83AC', '#38EDCA', '#C3A1B2', '#1A3C2B'];
var currentIndex = 0;

function changeBackground() {
    setTimeout(function() {
        if (shades.length == currentIndex) {
            currentIndex = 0;
        }
        $('body').css("backgroundColor", shades[currentIndex++]);
        changeBackground();
    }, 2000);
}
changeBackground();

})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The div content is aligning at the baseline rather than the middle

The social icons on my website are currently displaying at 40x40, with the text appearing below them. I am looking to center the text within the icons themselves. Any tips on how I can achieve this? Your help is much appreciated! Check out the fiddle here ...

Is it possible to conceal a link once it has been visited?

I am trying to figure out how to remove a link from a page once it has been visited. However, I am facing privacy restrictions with the :visited pseudo-class. Is there a way to achieve this without using display: none? For example: .someclass a:link {dis ...

Geometry is making its debut appearance in ThreeJS for the very first time!

Currently, I am experimenting with a simple script using ThreeJS to create a point wherever you click on the screen. Below is the function responsible for adding the point: function addPoint(coord){ var geometry = new THREE.BufferGeometry(); var verti ...

Transferring JSON encoded information from a controller to a view via ajax within the CodeIgniter framework

After selecting data from the controller, I want to display it on the view using a Bootstrap template. To achieve this, I need to place the following code in my controller: $data['sidebar']='member/dokter/sidebar_psn'; $data['cont ...

Converting between GPS degrees and decimal values using jquery, javascript, and PHP: A comprehensive guide

Is there a way to convert GPS degree to decimal values or vice versa? I am working on developing a feature where users can input an address and retrieve the GPS values in both degree and/or decimal format. However, my main challenge is understanding how t ...

Choose the desired options to add to the selection box

Here is a question that I have: <select class="myselect"> <option value="option 1">option 1</option> <option value="option 2">option 2</option> <option value="option 3">option 3</option> <option value="option 4 ...

Stop using the jQuery POST method after receiving a message indicating that the entry already exists in the database

Is it possible to stop the jQuery process once I receive a message indicating that data already exists in the database? I need to first check the ID, and if it does not exist, then insert it into the database using $.post("process.php"). $.post("checkda ...

Prevent draggable canvas elements from overlapping using jQuery

I'm currently working on a project where I need to make three canvas elements draggable while preventing them from overlapping each other. After researching similar issues, I came across the "jquery-ui-draggable-collision" library. Here is the code I ...

My React app experienced a severe crash when trying to render an animation in L

Currently, I am working on a React application that was set up using Vite. I recently incorporated an animation using Lottie, and although I was successful in implementing it, I encountered a problem when navigating between different pages of my applicati ...

Email the jQuery variable to a recipient

I'm facing an issue with sending a jQuery variable containing HTML and form values via email using a separate PHP file with the @mail function. My attempt involves using the jQuery $.ajax function on form submit to send this variable, but unfortunate ...

Crisp edges and corners casting shadows in Threejs BoxGeometry

I created a structure using BoxGeometry, with a DirectionalLight rotating around it. However, I am facing an issue with aliased light bleed in the corners. I've attempted adjusting the shadow.mapSize, the blur radius, and the renderer.shadowMap.type, ...

PointerLockControls maintains a constant speed without slowing down (threejs)

I have integrated THREE.PointerLockControls into my project following the implementation demonstrated in this example (view code). The code seems to be accurately translated from the example, but I am facing issues with deceleration of the controller once ...

The header row in my table multiplies each time an AJAX call is made

HeaderRowMultiplesEachTimeAjax My web grid table in JavaScript consists of a complete HTML table. The top header, which acts like a colgroup caption table, is built through JavaScript insertion as shown below: var headerRow = "<tr><th colspan=&a ...

Creating a fresh shortcut on the selenium IDE

Is there a way to customize shortcuts in Selenium IDE by modifying its code? For instance, I would like to set the shortcut ctrl + p for the action run test case, similar to how the save action is assigned ctrl + s. I've searched for the JavaScript ...

Express encountered an unexpected error when attempting to navigate to the client directory

I am attempting to send the index.html file from my client directory, located at the same level as my server directory. However, I am encountering the following error: TypeError: undefined is not a function at Object.handle (/myapp/server/routes/routes.js ...

Transforming table data into a JSON format

My goal is to generate a specific JSON format from a table. The table consists of rows and 4 columns. You can view my table here. I aim to create a JSONArray based on the table. The first value in the left column serves as the key in the JSON, while the la ...

Learn how to keep sessionStorage state synchronized across ReactJS components

Within my application, there is a React component responsible for displaying a list of numbers while also keeping track of the total sum of these numbers using sessionStorage. Additionally, another component provides an <input /> element to enable u ...

The request body for MERN full stack development is returning empty

I am currently facing an issue while trying to establish a connection between my client and the backend. Here is the snippet of code I am using: //client const body = { email: value, }; axios.get("http://localhost:5000/checkEmail", body) // ...

What is the process of manually loading webpack async chunks in the event that a dynamic import fails to load the file?

Async chunks in webpack can be created by using Dynamic Imports (for example: import('./ModuleA.js');). If the dynamic chunks fail to load, I want to retry loading them from another location. After grappling with the issue and delving into babel ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...