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>
percircle.js is a lightweight jQuery plugin used to create a pure CSS circle / ring to represent percentage data using CSS3 transforms and a little JavaScript. Great for creating progress bars or loading indicators for your web application. 1. Include jQuery library together with the jQuery percircle's JavaScript and style sheet on the web page.
Let’s start with an easy example. Take a look at the following JavaScript code: //Our number. var number = 120; //The percent that we want to get. //i.e. We want to get 50% of 120. var percentToGet = 50; //Calculate the percent. var percent = (percentToGet / 100) * number; //Alert it out for demonstration purposes.
The way it works is that each time an element is clicked, the counter (which starts at 0) goes up by one. The counter can be applied to the clicking of any particular elements or multiple elements, and you can choose whether or not to display it somewhere on your page or site, or log the counter to the console, or use the counter in a function.
Create the html structure for the percentage circle. class="big": big percentage circle. "small" = small size. Empty = medium size 3. Activate the plugin and done.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With