6

I tried to create a percentage counter but it doesn't do something that I need. It just shows 100%. However I need to show all 0 to 100% step by step! How should I change it?

setInterval(function per(p = 0) {
  for (p = 1; p <= 100; p++) {
    $(".percentage").text(p + "%");
  }
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="percentage"></p>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

11

The issue is because the for loop runs in a fraction of a second, regardless of the setInterval.

To fix this you could change your logic to use recursion and then delay each iteration by 1 second, like this:

function updatePercentage(p) {
  p = p || 0;
  $(".percentage").text(p + "%");
  if (p < 100) {
    setTimeout(function() {
      updatePercentage(++p);
    }, 1000);
  }
}

updatePercentage();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="percentage"></p>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339