LoginSignup
3
3

More than 3 years have passed since last update.

Javascriptで数値のカウントアップ

Last updated at Posted at 2018-07-14

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>
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3