Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

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

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>
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
3
Help us understand the problem. What are the problem?