Web開発用メモ。数値のカウントアップ。
See the Pen CountUp by snst.lab (@snst-lab) on CodePen.
<html>
<div id="countup">100 Likes</div>
<script>
setInterval(async function(){
await $('#countup').text('100 Likes');
await $('#countup').countUp(50,1000);
},4000);
const sleep = (time) => {return new Promise(resolve => {setTimeout(() => {resolve()}, time)})};
/**
* @int tick 刻み数
* @float timeout カウントアップ終了までのミリ秒数
*/
$.prototype.countUp = async function(tick,timeout){
const countMax = this.text().replace(/[^0-9.]/g, "");
const unit = this.text().replace(/[0-9.]/g, "");
const time = timeout/tick;
const step = countMax/tick;
var count = 0;
while(count < countMax){
await sleep(time);
this.text(Math.floor(count*1000)/1000 + unit);
count += step;
}
this.text(countMax + unit);
}
</script>
</html>