Delay occurs unexpectedly when adding a class with jQuery to multiple elements

I am in the process of creating a flipping counter that is designed to change colors once it reaches a certain target number (in this case, 1000). However, I am noticing that the different sections of the counter do not change color simultaneously, there seems to be a delay between each tile of the counter...

To trigger the color change, I am using a basic jQuery addClass method:

$("#rhcounter .count").addClass("red");

Any thoughts on what might be causing this issue?

You can view the fiddle here: http://jsfiddle.net/ka6ke28m/6/

Appreciate any help or suggestions! Thank you!

Answer №1

One of the main issues to address:

Significant processing resources were being wasted due to excessive use of jQuery selectors. It is recommended to minimize the use of selectors, especially complex ones, to optimize performance. This has been addressed in the optimized version.

Another critical issue to resolve:

A visual glitch has been observed in certain browsers, which has been rectified by replacing the background: property with background-color:. This change ensures that the background color is filled without triggering a complete re-render of the area.

Addressing the third concern:

The persistence of the color blue on the screen was attributed to slow repainting, which has been significantly improved by implementing the previous fixes. Additionally, specific CSS animations targeting the red class have been incorporated to further enhance performance. Further enhancements can be explored based on the identified causes of slow repainting (e.g., implementing separate CSS animations for blue and red elements).

For a visual representation of the optimized solution, refer to:

http://jsfiddle.net/TrueBlueAussie/ka6ke28m/10/

$(function () {
    // JavaScript code for optimized functionality
});

Answer №2

the issue was occurring because the color was being changed before the text. I reorganized the if condition and now it should work as expected SEE DEMO

$(window).load(function() {
    var total = 1000, current = 950, timeout = 150, inc = 7,
        prevTiles = ["0","0","0","0"],
        interval = setInterval(function(){increase()}, timeout),
        increase = function () {
            current += inc;

            if (current >= total) { 
                clearInterval(interval);
                current = total;
            }



            var tiles = [false, false, false, false], 
                currStr = (current+"").split("").reverse().join("");

            for (var i = 0; i < currStr.length; i++) {
                if (currStr[i] !== prevTiles[i]) { 
                    tiles[i] = true; 
                    prevTiles[i] = currStr[i];
                }
            }

            tiles.forEach(function (tile, index) {
                if (!tile) { return; }

                $("#rhcounter > div[class~='tile"+index+"'] > span[class~='curr']").each(function() {
                    $(this).text($("#rhcounter > div[class~='tile"+index+"'] > span.count.next.top").text());
                });
                $("#rhcounter > div[class~='tile"+index+"']").removeClass("flip");
                setTimeout(function(){$("#rhcounter > div[class~='tile"+index+"']").addClass("flip");}, 5);

                var top = $("#rhcounter > div[class~='tile"+index+"'] > span.count.next.top"),
                    bottom = $("#rhcounter > div[class~='tile"+index+"'] > span.count.next.bottom"),
                    delay = (index === 0 ? timeout : 250);

                setTimeout(function(){ top.text(prevTiles[index]); }, delay/2);
                setTimeout(function(){ bottom.text(prevTiles[index]); }, delay/2);
            });
         if (current === total) { 
                $("#rhcounter .count").addClass("red");
            }};
});

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

Angular UI directive for modal confirmation

Looking to create a custom Angular directive using angular-bootstrap that mimics the confirm() function. Check out the visual result and desired behavior in this plunk: http://embed.plnkr.co/27fBNbHmxx144ptrCuXV/preview Now, I want to implement a directi ...

When a sidebar is added, Bootstrap 5 cards that are supposed to be displayed in a row end up being shown in a column instead

When I have a row of Bootstrap 5 cards that display correctly, but then add a sidebar that causes them to stack in a column instead of remaining in a row. How can I maintain the row layout even with the addition of a sidebar using specific CSS classes or p ...

What is the process for integrating three.js code manually into an iframe?

I recently posted a question on Stack Overflow inquiring about how to input code into an iframe without using a file or URL. While I was successful with simple cases like <h1>Hello World</h1>, my ultimate goal is to integrate three.js into thes ...

What event gets triggered in the Google search bar?

When we type something in the Google search box, auto-complete results appear. After selecting one, it automatically executes without needing to trigger focusout() or any click(). How is this functionality created? ...

Enhancing Data Tables with Jquery: Implementing Column Filtering for Multiple Elements within Table Cells

I am looking to utilize jQuery datatables for filtering a column that may contain multiple values within a single td. To achieve this, I referenced the example provided in the datatables documentation. In the image below, my goal is to filter the office ...

"Error message when iterating through JSON using jQuery: 'a' is

I've come across similar discussions on this topic, but I haven't found a solution for looping through an array of key-value pairs in the following format: { "quotes": [ { "author": "Author One", "quote": "Quote One" }, { ...

Can someone help me figure out how to increase the values of two specific attributes within a class?

Currently facing a challenge with adjusting the number of likes and comments using increment for properties 'numberOfLikes' and 'comments'. Unsure whether to utilize a for loop or just the increment operator. Still new to coding, so apo ...

How can I specifically disable the next month in MUI Datepicker?

Employing MUI version 5, how can I disable only the next month in the datepicker while keeping the others functional? ...

Enhanced button effect: image shaded on hover

Can someone help me figure out how to make the button and image darker when hovered over? I tried something but it didn't work... Here is a demonstration: http://jsfiddle.net/h2o8w5y6/ <!--- example code snippet --> <div class="col-lg-4 ...

Leveraging Next Js with an external REST API for streamlined authentication and authorization functionality

I am currently working on transitioning my existing application that was developed with Node.js and Express, along with a front end built using create-react-app with Redux, to Next.js. However, I have hit a roadblock as I am unsure of the correct method ...

CORS request results in unsuccessful cookie setting in browsers except for Firefox where Set-Cookie header is detected; notably, Chrome does not show the header

I'm experiencing an issue with setting cookies from a NodeJS server to the client using JQuery and AJAX. Despite seeing the Set-Cookie headers in the response, the cookies are not showing up in the document.cookie string. I would greatly appreciate it ...

Tips for updating form values with changing form control names

Here is an example of a form I created: public profileSettingsGroup = new FormGroup({ firstName: new FormControl('Jonathon', Validators.required) }) I also have a method that attempts to set control values in the form: setControlValue(contro ...

What is the best way to manage data in a single-page application and retrieve it after the page has been refreshed?

Lately, I’ve encountered an issue with data storage in a single-page application. I’m seeking some guidance on how to effectively store data and retain it after refreshing the page within a Single Page Application. As an example, let's say I hav ...

Exploring Globalization in NextJS

As I work on setting up a NextJS project that requires i18n support, I have come across various libraries dedicated to internationalization. Are these libraries truly necessary? After reviewing the documentation, I find the idea of keeping an object at a g ...

Creating a dynamic onclick function that depends on a variable passed from a while loop in PHP

If you're familiar with PHP, I have a scenario for you. Let's say there's a list of items generated using a while loop in PHP. Each item has a sub-list that should only appear when clicked on. I tried using the onclick function in jQuery but ...

Adding information to a JSON file using JavaScript: A step-by-step guide

Struggling to develop a basic Discord.js bot, I've hit a roadblock when it comes to incorporating user input into an array stored in a json file. My goal is to maintain a single json file to hold data that the bot can utilize, including a collection ...

UI-Router: What is the best way to access a page within my project without adding it as a State?

Currently in the process of learning Angular and UI-Router. Initially, I followed the advice of many and chose to utilize UI-Router. In my original setup, the login page was included in all States. However, I decided it would be best to keep it as a separ ...

The CSS is getting overridden by the a:-webkit-any-link user agent stylesheet

I've found myself faced with a page full of lists and links that I need to style individually. No matter what I try, the fonts and colors keep getting overridden by an unknown user agent stylesheet. I've experimented with styling the divs using c ...

Innovative: Enhancing column width dynamically without compromising grid integrity

Currently, I am utilizing Bourbon's Neat library to structure my grid system. Within my code, I have the following setup: section { @include outer-container; aside { @include span-columns(3); } article { @include span-columns(9); } } The chal ...

Maximize background width with a gradient that is compatible with web-based email clients such as Outlook and Gmail

Recently, I was given the task of creating a newsletter to support cancer fundraising. Excitedly, I accepted the assignment but encountered a frustrating issue with web-based email clients (such as outlook.com and gmail.com) not accepting some of my stylin ...