JSFiddle - React, Tailwind, and code Playground
HTML
<div id="foo"></div>
<div id="bar"></div>
JavaScript
animate("99%", $("#foo"));
//animate("75%", $("#bar"));
function loop(clr, clr2, ele, rand, last, delay) {
clearInterval(clr);
clearInterval(clr2);
inloop(clr, clr2, ele, rand, last, delay);
if (rand >= last) {
clearInterval(clr);
clearInterval(clr2);
}
else {
clr2 = setTimeout(function () {
loop(clr, clr2, ele, rand, last, delay);
}, 2500);
}
}
function inloop(clr, clr2, ele, rand, last, delay) {
ele.html((rand += 1) + "%");
if (rand >= last) {
clearInterval(clr);
clearInterval(clr2);
}
else {
clr = setTimeout(function () {
inloop(clr, clr2, ele, rand, last, delay);
}, delay);
}
}
function animate(end, display) {
var clr = null;
var clr2 = null;
var ele = null;
var rand = 0; // initial number
var last = 99; // last number
var delay = 5; // inner loop delay
ele = display;
ele.html("0%");
var idx = end.indexOf("%");
if (idx >=0) {
end = end.substring(0,idx);
}
last = parseInt(end);
loop(clr, clr2, ele, rand, last, delay);
}