Issues with Jquery Animate failing to complete its animation

My webpage has several animations running, and it seems that one particular animation is stuttering and not completing properly at times.

The animation I have written is meant to animate percentage bars on the page.

I attempted to add a timeout function to allow the other animations to finish before starting this one, but the timeout doesn't seem to work as intended. It triggers immediately after the page loads. Any advice on ensuring that my percentage animations complete smoothly would be greatly appreciated.

function animatePercentages()
{
  $('.bar-percentage[data-percentage]').each(function () {
    var progress = $(this);
    var percentage = Math.ceil($(this).attr('data-percentage'));
    $({countNum: 0}).animate({countNum: percentage}, {
      duration: 1000,
      easing:'swing',
      step: function() {
        // Actions to perform during each count
        var pct = '';
        if(percentage == 0){
          pct = Math.floor(this.countNum) + '%';
        }else{
          pct = Math.floor(this.countNum+1) + '%';
        }
        progress.text(pct) && progress.siblings().children().css('width',pct);
      }
    });
  });
}

$(document).ready(function() {
  setTimeout(animatePercentages(), 1000);
});

Here is an example of the HTML code for the animated bar that failed at 91%:

<div id="bar-5" class="bar-main-container" style="margin-left:auto;margin-right:auto;background:#cb0050;max-width: 250px;">
  <div class="wrap">
    <div id="bar-percentage13" class="bar-percentage" data-percentage="100">91%</div>
    <div class="bar-container">
      <div class="bar" style="width: 91%;"></div>
    </div>
  </div>
</div>

Answer №1

Initially, you are invoking the dopercentage() function right away and then passing its result to setTimeout.

setTimeout actually requires a function reference, not the outcome of a function call.

To rectify this, simply pass the function reference (name):

$(document).ready(function() {
  setTimeout( dopercentage, 1000);
});

In addition to that, I just had to eliminate the initial 91% text from the example. When the code didn't execute as expected, I ended up with your test value :)

JSFiddle: https://jsfiddle.net/Ly3vj12d/1/

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

Data not being read in Meteor with MongoHQ Mongodb on Heroku

I have successfully converted the Leaderboard meteor app () to a simple Node.JS app using Demeteorizer (https://github.com/onmodulus/demeteorizer). To connect my app to an external Mongohq database, I followed the guidelines outlined at and successfully ...

A guide to invoking a function from another component in Angular

analytics.js fetchAnalyticsData() { this.loading.today = true; this.loading.daily = true; const metrics = ['VISITS', 'PAGE VIEWS', 'CONVERSION RATE', 'BOUNCE RATE']; const analyticsModules = [ ...

Selenium EventFiringWebDriver JavaScript: There is a SyntaxError due to a missing closing parenthesis after an argument in

Attempting to run a javaScript command through the EventFiringWebDriver class in Selenium. EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver); eventFiringWebDriver.executeScript("document.querySelector('[ng-reflect-title=&ap ...

Using UI Bootstrap modal within a directive allows for the functionality of multiple modals, with the unique feature

Check out this Plunkr to see the issue I'm facing with two modals, each within separate directives named modal-one and modal-two. The problem arises when clicking on the button for modal two, as only modal one is being opened. I suspect that the iss ...

Why is this error occurring: "Uncaught ReferenceError: fail is not defined"?

Currently, I am working on developing a dynamic Signup form. The creation of the form is complete, along with the implementation of various functions to validate the input entries. However, an issue arises where the variable intended for displaying an er ...

Include the URL as a parameter in the query when utilizing Tesseract OCR

I have successfully implemented the tesseract ocr, but I am wondering if it is possible to run tesseract with a URL as a parameter. I want to achieve the following: localhost/test.html/?othersite.com/image/image2.jpg Here are some image URLs for demonst ...

The plugin that simplifies adding and removing form fields in jQuery

I am in search of a quality plugin that can easily add or remove a set of form fields on a webpage. I came across this one , which seems to fit my requirements. However, I am exploring other options to see if there is an even better plugin available. Ther ...

How can you handle events on DOM elements that haven't been created yet in JavaScript?

In my JavaScript module, I have the following code: EntryController = function$entry(args) { MainView(); $('#target').click(function() { alert('Handler called!'); }); } The MainView() function includes a callback ...

Install only the necessary components from React Material UI

Is it possible to selectively install specific components from React Material UI? Specifically interested in the Autocomplete component, which can be found at this link. ...

Tips for effectively utilizing the Angular ngIf directive for toggling the visibility of elements

<div *ngFor = "let element of myElements, let i=index" [ngClass]="{'selected':element[i] == i}"> <li> Name: {{element.element.name}}</li> <li> Description: {{element.element.description}}</li ...

A guide to effortlessly importing JSON data with Svelte

During my recent testing, I have successfully utilized the below code to work with a component: <script> import x from "/path/to/x.json" </script> This code snippet effectively loads the json file into the variable x. Now my objecti ...

Dynamically Allocating Page Heights

I am tasked with creating an ASP.NET MVC page that will display a template of controls. The controls will be retrieved from an XML file. One issue I am facing is that the number of controls is not fixed, so the page height needs to be dynamic. Our site has ...

Having trouble with basic HTML/CSS functionality not functioning properly

It appears that the stylesheet is correctly linked, but it seems like there might be an issue with the HTML/CSS code. I haven't worked on HTML/CSS in a while, so I could be missing something obvious. Can you help figure out what's wrong? ...

The custom service is failing to load, in the simplest terms possible

After creating a dataService.j that contains the following: angular.module('dataService', []) .service('gameDataService', function() { var _gameData = { loggedIn: "false", gameJoined:"false", tableFu ...

Unable to upload file to firebase storage - encountering technical issues

After following the documentation on firebase storage, I still can't seem to get my file upload to work properly. Using react, my goal is to successfully upload a file to firebase storage. However, I keep encountering an error message: TypeError: th ...

Vue encounters an issue when trying to access a specific field within an array of objects

Consider the following data structure: rules:[ 0:{ subrule1:'', subrule2:'', subrule3:'' }, 1:{ subrule1:'', subrule2:'', subrule3:'' } ...

Eliminate unseen and unique characters in Java or JavaScript

I am looking to eliminate the [LS], [LS] character that only shows up when pasted in Notepad++. This data was inserted in a way that it is hidden and can only be seen on a UTF-8 encoding editor. Additionally, I want to remove characters like phone; email; ...

Require assistance in creating an event that triggers an action when clicked, while another event remains inactive upon clicking

<FullCalendar allDaySlot={true} eventClick={(info) => this.openReservationInfoModal(info.event)} events={[...milestones.map(milestone => ({ id: milestone.id, ...

Tips for effectively showcasing a leaflet map within a NuxtJS project

I've encountered an issue with my map while working on a project using NuxtJS and the library . The map is not displaying correctly. Below is my code snippet and a screenshot of the problem: map.vue : <template> <div id="map-wrap" ...

Updating ReactJS Context within a class-based component

I've been experimenting with various online tutorials on utilizing "Context" in ReactJS, but I'm encountering difficulties when attempting to update the context in child components. The foundation of my code is sourced from : I primarily use cla ...