JavaScript slowness

Currently, I am developing a test page that consists of buttons triggering various scripts. One of the functionalities I am trying to implement is changing the background color every second for 5 seconds, cycling through a total of 5 different colors. Despite researching and learning about setInterval and setTimeout, I still find it challenging to grasp.

The desired sequence:

x
wait 1 sec   
y
wait 1 sec  
z
wait 1 sec
etc...

I initially attempted to incorporate all these changes within one function but encountered complexity in referencing a function within setTimeout(function, 500).

Therefore, I resorted to creating individual functions for each color change, as shown below. Subsequently, I created a master function named disco() to invoke each background alteration.

To be frank, I am quite confused at this point. The provided code should illustrate my attempts, but unfortunately, the desired outcome was not achieved, leading me to a dead-end.

I would deeply appreciate an explanation or guidance on how to accomplish this task effectively. Thank you!

function disco() {
    setTimeout(aquaman, 500);
    setTimeout(pinkman, 500);
    setTimeout(blueman, 500);
    setTimeout(redman, 500);
    setTimeout(brownman, 500);
}

function aquaman() {
    document.body.style.backgroundColor = "aqua";
}

function brownman() {
    document.body.style.backgroundColor = "brown";
}

function redman() {
    document.body.style.backgroundColor = "red";
}

function pinkman() {
    document.body.style.backgroundColor = "pink";
}

function blueman() {
    document.body.style.backgroundColor = "blue";
}

Answer №1

    var bgColors = {
        colors: ['red','blue', 'green'],
        nextIndex: 0,
        getNextColor: function(){
            return this.colors[this.next++ % this.colors.length];
        }
    };

    setInterval(function () {
          document.body.style.backgroundColor = bgColors.getNextColor();
        }, 1000);

Answer №2

Utilize the code snippet provided below to dynamically alter the background color to the next one in the predefined array. Embed an interval function to regulate the time duration for each color transition. Don't hesitate to reach out with any queries regarding the functionality:

    function adjustBackgroundColor(){
       var colors = ['orange', 'green', 'purple', 'yellow', 'cyan'],
           currentColor = ( ( colors.indexOf( document.body.style.backgroundColor ) + 1 ) % 5 );
       
       if(currentColor === -1) currentColor = 0;

       document.body.style.backgroundColor = colors[ currentColor ];
    }

    setInterval(adjustBackgroundColor, 1000)

Answer №3

setTimeout() is a tool used for asynchronous operations. It allows you to schedule functions to be executed by the browser after a specified amount of time in milliseconds. When multiple setTimeout() calls are made with the same timeout value, all those functions will run almost simultaneously.

Consider the following scenario:

function disco()
{
setTimeout(aquaman, 500);
setTimeout(pinkman, 1000);
setTimeout(blueman, 1500);
setTimeout(redman, 2000);
setTimeout(brownman, 2500);
}

This code accomplishes the intended outcome, but it can be improved for better efficiency and readability as shown below:

function aquaman() {
  document.body.style.backgroundColor = "aqua";
}

function brownman() {
  document.body.style.backgroundColor = "brown";
}

function redman() {
  document.body.style.backgroundColor = "red";
}

function pinkman() {
  document.body.style.backgroundColor = "pink";
}

function blueman() {
  document.body.style.backgroundColor = "blue";
}

function disco() {
    var timeout = 500;
    var funcs = [aquaman, brownman, redman, pinkman, blueman];
    funcs.forEach(function(func) {
      setTimeout(func, timeout);
      timeout += 500;
    });
}

The above code eliminates some redundancy, but there is still room for improvement by further optimizing the function definitions as follows:

function disco() {
    var timeout = 500;
    var colors = ['aqua', 'brown', 'red', 'pink', 'blue'];
    colors.forEach(function(color) {
      setTimeout(function() {
        document.body.style.backgroundColor = color;
      }, timeout);
      timeout += 500;
    });
}

This modified code provides an efficient solution to your issue.

Answer №4

 var colors = ['red','pink','blue'];
    var currentColor = 0;
    function changeColor() {
      setTimeout(function() {
        if(currentColor === colors.length) {
           currentColor = 0;
        }
        document.body.style.backgroundColor = colors[currentColor];
        changeColor(currentColor++);
      }, 500);
    }
    changeColor();

Utilize recursion within setTimeout to run the changeColor function repeatedly with a delay of 500ms per execution.

Answer №5

Simple Example:

<script>

(function changeColor() {
   setTimeout(function switchToAqua() {document.body.style.backgroundColor = "aqua";}, 0);
    setTimeout(function switchToPink() {document.body.style.backgroundColor = "pink";}, 1000);
    setTimeout(function switchToBlue() {document.body.style.backgroundColor = "blue";}, 2000);
    setTimeout(function switchToRed() {document.body.style.backgroundColor = "red";}, 3000);
    setTimeout(function switchToBrown() { document.body.style.backgroundColor = "brown";}, 4000);
})();
</script>

View Demo: http://jsbin.com/qumagozosi/edit?html,js,output

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

determining if two words are synonymous or not

For this task, you are required to develop a program that can determine if two words are synonymous. A synonym dictionary will be provided with pairs of corresponding words. Your program will then need to respond to queries regarding whether two given word ...

Combining Multiple Arrays into a Multidimensional Array

I'm struggling to find information on how to combine multiple arrays of the same length into a multidimensional array. For example, I have three arrays: array1 = [value1a1, value2a1, value3a1]; array2 = [value1a2, value2a2, value3a2]; array3 = [value ...

Why won't the click event work in Vue when using v-if or v-show?

Attempting to trigger a click event from a div, but if v-if false is present during component rendering, the click event does not work. Here's the code snippet: export default { name: "ProSelect", data() { return { isActive: false ...

Setting up a connection between an Express server and a Mongoose database in

As someone who is relatively new to the express framework and mongoose database, I have mainly worked with relational databases in the past. I am attempting to create a database using the script below. Currently, mongod.exe is running and listening on loca ...

Featuring data utilizing Ajax JSON in CodeIgniter

How can I display the data using AJAX? After making the data call to the controller, the JSON data is available but the data for "name", "address", and "telp" based on the "id_data" is not showing up. How can I display this data? Views <input id="id_d ...

Create a div element that expands to occupy the remaining space of the screen's height

I am trying to adjust the min-height of content2 to be equal to the screen height minus the height of other divs. In the current HTML/CSS setup provided below, the resulting outcome exceeds the screen height. How can I achieve my desired effect? The foote ...

Could someone provide me with guidance on how to troubleshoot this error message?

[0] Unhandled rejection MongoError: (Unauthorized) not authorized on admin to execute command { listIndexes: "sessions", cursor: { } } [0] at MongoError.create (/Users/biggahd/Desktop/Mars-EMS-1/backend/node_modules/mongodb-core/lib/error.j ...

Execute the script when the document is fully loaded

Is there a way to show a dialog in jQuery when the document loads without using <body onload="showdialog();">? Can the javascript code be placed in the main div or footer div to work like the onload event? <body onload="$('#dialog').sli ...

Merge JavaScript Functions into a Single Function

I am looking to streamline the following javascript code into a single function by utilizing an array of ids instead of repetitive blocks. Any suggestions on how to achieve this would be greatly appreciated. Currently, in my code, I find myself copying an ...

Creating Vue Components indirectly through programming

My goal is to dynamically add components to a page in my Vue Single file Component by receiving component information via JSON. While this process works smoothly if the components are known in advance, I faced challenges when trying to create them dynami ...

Setting up a straightforward static server using node.js

var express = require('express'); var app = express(); app.use('/', express.static('./')); app.listen(80); Error message encountered when running "node server.js" in the CLI: events.js:160 throw er; // Unhandled ...

Should a MEAN stack app require the use of two servers in order to run?

Currently, I am in the process of developing a MEAN stack application which involves using MongoDB, ExpressJs, Angular 6, and NodeJs. One issue I am facing is determining whether two servers will be necessary to run the app simultaneously. Specifically, o ...

Enhancing arrow cone spin with ThreeJs

My arrow function is supposed to connect pick and place points using QuadraticBezierCurve3 and ConeGeometry, but the rotation of the cone doesn't align perfectly with the curve as shown in the snippet below! I'm seeking advice on how I can enhan ...

The issue arises from the fact that the Bootstrap modal fails to open automatically

Having trouble getting my bootstrap modal to open on page load, even though the button to trigger it is working fine. Here is my code: <div id="myModal" class="modal fade" role="dialog"> <div class=" ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

What is the best way to dynamically load content as it enters the viewport using JavaScript or jQuery?

I have implemented a stunning animation to the h1 element using a function, but now I want the animation to trigger only when the h1 element enters the viewport as the user scrolls down. Currently, the animation occurs as soon as the page is loaded, even ...

Guide to encapsulating an asynchronous function in a promise

I am in need of wrapping an asynchronous function within a promise to ensure synchronous execution. The reason behind this is that I must obtain a result from the asynchronous function before proceeding with the program's execution. Below is the rele ...

Exploring the intricacies of Implementing Chromecast Networks, with a curious nod towards potentially mirroring it with

In my current project, I am aiming to replicate the functionality of a Chromecast on a Roku device. To achieve this, I need to first discover the Roku using UDP and then send an HTTP POST request to control it. During a recent developer fest where I learn ...

Localization of text in jQuery timeago.js

I have implemented J Query time ago to display date and time on my website. I am currently working on a multilanguage website where I want the time ago message to show as "1 min ago" for English users and "1 دقیقه قبل" for Farsi users. Can I achi ...

Using Axios to fetch data and populating select dropdown options in a Vue component

I am currently working on integrating the response data values with my multiselect options. Although the console log displays the returned results, I'm facing difficulty in connecting them to my multiselect options. When I enter 'Day' into ...