JS/jQuery number increasing animation

2019-02-07 15:31发布

问题:

Let's say i have a div called .number containing a number.

i want to increase that number to a new one dynamically with a counter increasing effect like this one in the bottom.

Any lightweight solutions?

Thanks

回答1:

$(function() {
  var ele = $('#haha');
  var clr = null;
  var rand = (Math.random() * 100000) >> 0;
  (loop = function() {
    clearTimeout(clr);
    (inloop = function() {
      ele.html(rand+=1);
      if(!(rand % 50)) {
        return;
      }
      clr = setTimeout(inloop, 30);
    })(); 
    setTimeout(loop, 2500);
  })();
});

DEMO

Edit :

$(function () {
    var ele = $('#haha');
    var clr = null;
    var rand = Math.floor(Math.random() * 100000); // just a random number(initial number)
    loop();
    function loop() {
        clearTimeout(clr);
        inloop();
        setTimeout(loop, 2500); //call 'loop()' after 2.5 seconds
    }
    function inloop() {
        ele.html(rand += 1);
        if (!(rand % 50)) {
            return;
        }
        clr = setTimeout(inloop, 30); //call 'inloop()' after 30 milliseconds
    }
});

$(function() {
  var ele = $('#haha');
  var clr = null;
  var rand = (Math.random() * 100000) >> 0;
  (loop = function() {
    clearTimeout(clr);
    (inloop = function() {
      ele.html(rand += 1);
      if (!(rand % 50)) {
        return;
      }
      clr = setTimeout(inloop, 30);
    })();
    setTimeout(loop, 2500);
  })();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="haha"></div>