1

I am trying to set the duration of my counter to be slow without having a large duration number set in the code for example:

duration: 99999;

Originally I had the counter set to a low number but the count is to reach 1,000,000,00 but i want to be able to control how fast this counts.

Here is how I currently have it set up.

<div class="counter" data-count="1000000">0</div>

and my JS is as follows:

$('.counter').each(function() {
var $this = $(this),
  countTo = $this.attr('data-count');

$({ countNum: $this.text()}).animate({
countNum: countTo
},

{

duration: 99999,
easing:'linear',
step: function() {
  $this.text(Math.floor(this.countNum));
}
});  
});

I am a Junior at this so any other recommendations would be appreciated.

Thanks

1 Answers1

2

If you want to set how quickly the count is being made, you can try setting the duration (which is measured in milliseconds) to match the countTo value. For example, if you want an increment to be made every second, do: duration: parseInt(countTo)*1000.

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');

  $({
    countNum: $this.text()
  }).animate({
    countNum: countTo
  }, {
    duration: parseInt(countTo) * 1000,
    easing: 'linear',
    step: function() {
      $this.text(Math.floor(this.countNum));
    },
    complete: function() {
      // Ensure that the final value is updated correctly
      // ... especially when using very short durations
      $this.text(this.countNum);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter" data-count="1000000">0</div>
Terry
  • 48,492
  • 9
  • 72
  • 91
  • Excellent! Thank you very much! :) –  Oct 15 '16 at 12:55
  • @dcmagpies Just remember that even though the duration can be set to a very small value, the end result might not be accurate—you will need to use `complete: function(){...}` to manually set the final value then. – Terry Oct 15 '16 at 12:58