JQuery Count animation?

I have a counter that should count from $ 0 to $ 10,000 in x seconds (most likely 3 seconds).

Just plain text, sort of like a millisecond countdown timer, but up and with a dollar sign.

I would prefer not to use a bulky plugin, as it just needs to be scrolled through 1-10.00 in x seconds and updated every 100 ms.

I'm stuck on creating a loop to be updated, where do I start?


Here is what I got so far in the click event:

  function countUp() {
    console.log('counted');
    }

    setInterval("countUp()", 1000)
+3
source share
4 answers

I would use the code from http://www.mredkj.com/javascript/numberFormat.html to add commas:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

setInterval 1000, - :

var x = 1;
    var interval = setInterval( 
    function(){
        if (x < 10000){
            x = parseInt(x) + 100;
            if(x > 10000){x = 10000}
            $('#number').html("$" + addCommas(x));
            }},
            10);

, 3 , javascript . 10- 100 FireFox Google Chrome.

10 , , 10 000 . , x - 10 000. clearInterval(interval)

+1

jQuery ():

$(function(){
    var current = 0;
    var finish = 10000;
    var miliseconds = 3000;
    var rate = 20;

    var counter = setInterval(function(){
         if(current >= finish) clearInterval(counter);
         $("#div").text("$" + current);
         current = parseInt(current) + parseInt(rate);
    }, miliseconds / (finish / rate));
});
+3

, setInterval() .

, parseInt(), , , .

45 + 45 == 4545

parseInt (45) + parseInt (45)

use closure etc. Let me know if you need more help.

0
source

Just test this for fun, feel free to change, but you need:

var x = 0;
var total = 10000;
var seconds = 3;
var interval = 100;
var increment = Math.ceil(total / ((seconds * 1000) / 100));

var myInterval = setInterval(function(){
    if((x + increment) < total){
        x += increment;
    } else {
        x = total;
        clearInterval(myInterval);
    }
    console.log(x);

}, interval);
0
source

Source: https://habr.com/ru/post/1745187/


All Articles