-2

I am developing a game that will animate the money that is added or subtracted.

The jquery solution is here:

How to increment number using animate with comma using jQuery?

How can I do this in plain javascript?

I want to avoid using jquery

Community
  • 1
  • 1
Ismail
  • 8,904
  • 3
  • 21
  • 39
  • 1
    That's not an animation.. It's just the text content being updated very fast. – Lix Jul 27 '14 at 15:24

3 Answers3

2

In this solution, no jQuery is needed

var from=40000, to=50000;
function increment() {
    setTimeout(function() {
        from++;
        if(from <= to) {
            document.getElementById("test").innerHTML = from;
            increment();
        }
    }, 10);
}
increment();

Please visit the jsfiddle. http://jsfiddle.net/TTaA4/

Ruchir Gupta
  • 990
  • 3
  • 10
  • 20
0
    var counter = 0;

    var timer = setInterval(function () {
        if (counter >= 100 ) {
            clearInterval(timer);
        }

        counter++;
        // call numberWithCommas(counter) to get no.s with comma..
    }, 100);

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

the above code for comma function is shamelessly copied from https://stackoverflow.com/a/2901298/2466168

Community
  • 1
  • 1
Srinath Mandava
  • 3,384
  • 2
  • 24
  • 37
0

http://jsfiddle.net/2MwSv/

Try it out in your javascript console:

var a = 40000;
var b = 45000;
console.log(commaSeparateNumber(a));

function animate(opts) {

    var start = new Date;

    var id = setInterval(function () {
        var timePassed = new Date - start
        var progress = timePassed / opts.duration

        if (progress > 1) progress = 1

        var delta = progress;
        opts.step(delta)

        if (progress == 1) {
            clearInterval(id)
        }
    }, opts.delay || 10)

}

function commaSeparateNumber(val) {
    while (/(\d+)(\d{3})/.test(val.toString())) {
        val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }
    return val;
}


animate({
    delay: 10,
    duration: 3000,
    step: function (progress) {
        var difference = b - a;
        console.log(commaSeparateNumber(a + Math.round(progress * difference)));
    }
});

Sources:

http://javascript.info/tutorial/animation

How to increment number using animate with comma using jQuery?

Community
  • 1
  • 1
Ismail
  • 8,904
  • 3
  • 21
  • 39