JavaScript execution triggers DOM repaint in Chrome

For my upcoming course catered towards beginners with no programming experience, I want to demonstrate basic DOM-manipulation without involving async programming or callback functions.

I came up with the following idea:

function color(element, color) {
    element.style = "background: " + color + ";";
}

function wait(milliseconds)
{
  var e = new Date().getTime() + (milliseconds);
  while (new Date().getTime() <= e) {}
}

function disco() {
    var body = document.getElementById("body")
    color(body, "red")
    wait(500)
    color(body, "darkGreen")
    wait(500)
    color(body, "darkBlue")
}

disco()

While this script runs smoothly, the UI fails to update until the function completes, resulting in a blue background without showing red or green. Is there any way to trigger a repaint during the function execution?

I understand that this approach is not ideal for practical use, but my goal is to make it easy for newcomers to understand.

Answer №1

While you wait anxiously, the browser remains idle. This method is highly discouraged. Instead, consider setting up your party like this.

var body = document.body;
var colors = [ "purple", "teal", "gold" ];
var nextColor = 0;

function changeColor(element, color) {
    element.style = "background: " + color + ";";
}

function newColor() {
    changeColor(document.body, colors[nextColor%colors.length];
    nextColor++;
}

function discoLights() {
    setInterval(newColor, 500);
}

Please be aware that this snippet serves as a demonstration and has not been extensively tested.

Answer №2

If you want to add some color-changing effects to your webpage, you can achieve it using setTimeout and style.backgroundColor instead of the provided functions color() and wait(). Check out this custom disco function I created:

function disco(){

    var body = document.getElementById("body");
    var time = 0;

    for (var i=0;i<10;i++) // Let's change the background color 10 times just for testing purposes
    {
        setTimeout(function(){ body.style.backgroundColor = "red"}, time);
        time += 100;
        setTimeout(function(){ body.style.backgroundColor = "darkGreen"}, time);
        time += 100;
        setTimeout(function(){ body.style.backgroundColor = "darkBlue" }, time);
        time += 100;
    }

}

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

Launching a Node.js command-line interface to NPM, developed using TypeScript

I'm struggling with deploying my Node CLI tool to NPM. During development and testing, everything works fine. I can even use `npm link` on the repo without any issues. After successfully publishing and downloading the package, the application crashes ...

Encountering an issue with the node.js express server when fetching data

I'm running into an issue with the fetch function and node.js. When a button is clicked on my frontend, I want to send a post request to receive an array from my backend as a response. My backend is built using node.js with express, and I'm using ...

Applying a CSS transition to transform properties excluding rotation effects

I'm looking to apply a transitional animation to an element's transform property without affecting the rotation. Here is the code snippet: <html> <head> <link rel="stylesheet" href="style.css"> <script src="script.js ...

Using Jquery to make an Ajax request to a PHP script that retrieves JSON data

Hello, I am new to working with JSON. I have a PHP script that contains a multidimensional array, which is then encoded into JSON format like this: <?php header('Content-Type: application/json'); $lista = array ( 'Conoscenti'=&g ...

A dynamic context menu using jQuery within AJAX-loaded content

After spending hours searching for a solution without success, I am turning to this forum for help (I have come across similar questions but none of them have solved my issue). The problem I am facing is with implementing a custom context menu on a page t ...

When reference variables are utilized before being parsed, what happens?

I'm a beginner learning Angular and have a question regarding the use of reference variables. Here is an example code snippet: <div class="bg-info text-white p-2"> Selected Product: {{product.value || '(None)'}} </div> <di ...

retrieve the identification number associated with a specific value

How can I retrieve the value of this ID, which is sent from the controller and displayed in the table? https://i.sstatic.net/UbdxT.png This is my HTML code: <tbody class="no-border-x"> <tr> <td id="id"></td> <td i ...

Code has been loaded successfully for react-loadable Chunks, however it has not been

Encountering a problem while trying to implement chunks in my React app using react-loadable Everything functions perfectly on webpack-dev-server in development mode. However, when I build the project and deploy it to the server, async components are ...

Navigate through a variable amount of choices in a JSON array

Creating an MCQ application with questions having varying numbers of options can be challenging. For example, question 1 may have 4 options while question 2 may only have 2. A json array from the backend provides data indicating the number of options for ...

Is it possible to create a return using messageEmbed in Discord?

I have been working on creating a Discord bot that responds to the ! status command with the server status. I took inspiration from this existing bot. The only change I made was to ensure that the bot replies immediately to the ! status command without re ...

AngularJS redirection not fully functional

Having trouble with redirect in angularJS? For instance, everything works smoothly when a user logs in. If the user is logged in (information stored in local storage), they are automatically redirected to '/dashboard'. However, when the user lo ...

Express: router.route continues processing without sending the request

I've implemented the following code in my Express application: var express = require('express'); // Initializing Express var app = express(); // Creating our app using Express var bodyParser = require(' ...

In need of changing the date format post splitting

I need help converting a date from MM/DD/YY to YYYYMMDD The current code I have is giving me an incorrect output of 2211. How can I implement a check on the Month and Day values to add a leading zero when necessary? var arr = '1/1/22'; arr = NTE ...

Steps to include a title next to a progress bar:

Is there a way to achieve something like this? https://i.sstatic.net/dhO2f.jpg I attempted to use bootstrap but I ran into an issue where the title was slightly misaligned below the progress bar. Can someone offer assistance with this matter? Apologies i ...

Using Regex with JavaScript while ignoring letter case

I am trying to extract a query string from my URL using JavaScript, and I need to perform a case-insensitive comparison for the query string name. In order to achieve this, here is the code snippet that I am currently using: var results = new RegExp(&apos ...

What is the reason for the incompatibility between Bootstrap and Vanilla JavaScript?

Why does my slideshow crash when I use Bootstrap with vanilla JavaScript? It seems like there is a timeout or something... I'm not sure why this is happening. When I remove Bootstrap, the slideshow works fine. Here is my code: I attempted to remove ...

Transforming the Unix timestamp prior to transmission via JSON

Thank you for taking the time to address this situation. In my database, dates are stored as Unix timestamps. When I retrieve all the information using: while($row = mysql_fetch_assoc($result)) { $posts[] = $row; } /* ...

What is the solution for incorporating multiple elements in knockout's applyBindingsToNode function?

I am currently using knockout applyBindingsToNode to dynamically add and remove elements in order to update my html. I need to cut the binding, which is why I am utilizing applyBindingsToNode. In an example I have provided, if you click on the button "Reb ...

What is the best way to align row elements in Bootstrap?

Hey there everyone! I've been grappling with a challenge for the past few days on how to center the contents of a Bootstrap row. Let me elaborate: The row has 12 columns (as is standard in Bootstrap). However, in my design, I'm only utilizing 9 c ...

Unable to resolve the issue with mongoose's model overwrite error

Recently, I implemented the angular-fullstack generator and introduced a Model called person. However, upon attempting to require the person model in the seed.js file, an error is triggered. /Users/dev/wishlist/node_modules/mongoose/lib/index.js:334 ...