简体   繁体   中英

Trouble with Jquery Animate not finishing it's animation

I have a fair bit of animation running on my page, and I think its causing this particular animation to stutter, and then not finish its animation some of the time.

I have written this to animation some percentage bars on the page.

I have tried adding a timeout function so that it gives the other animation some time to finish up, however the timeout doesnt work and it seems to fire off immediately after the page loads. Any help making sure my percentages finish would be amazing

function dopercentage()
{
  $('.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() {
      // What todo on every 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( dopercentage(), 1000);
});

Here is a HTML example of what should be animated, but 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>

You are calling dopercentage() immediately, then passing the result to setTimeout.

setTimeout requires a function reference , not the result of a function call.

Just pass the function reference (name):

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

Aside from that, I just had to remove the initial 91% text from the sample. When the code was not firing I wound up with your test value :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM