views:

163

answers:

4

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

Just straight text, kind of like a millisecond countdown timer, but upwards and with a dollar sign.

I'd rather not use a bulky plugin as this just needs to loop through 1-10,00 in x seconds and update every 100ms or so.

I'm stuck at creating the loop that will update, where should I start?


Here is what I've got so far on a click event:

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

    setInterval("countUp()", 1000)
A: 

Create a function, then use setInterval() to update the function.

The function should be fairly dynamic, and should read the existing value, remember to use parseInt() to ensure you are calculating numbers, and not just concatenating strings.

45 + 45 == 4545

parseInt(45) + parseInt(45)

use closures, etc. Let me know if you need more help.

mike clagg
Maybe some code would help. I'll add what I've got so far.
Wes
A: 

Using jQuery (edited):

$(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));
});
bschaeffer
bah. This website is way too fast. Thanks a lot :)
Wes
I'd put a clearInterval in there, otherwise the script will keep running even after reaching 10000
Mike Robinson
Any idea how I can restart this when I fire the function again wtihout reloading the page?
Wes
@Mike, thanks... haven't worked with setInterval much... if at all (thanks to jQuery). I edited the answer.
bschaeffer
you can set a function that accepts the desired variables: `countUp(current, finish, duration, rate)` and just call it. I don't know that clearing the intervals will work each time you call it though.
bschaeffer
Your updated code give me: missing ; after for-loop initializer[Break on this error] for(var i = 0, i >= miliseconds / rate; i++)\n
Wes
Ooops! We found a straggler
bschaeffer
A: 

Just tested this out for fun, feel free to modify however 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);
Mike Robinson
+1  A: 

I would use 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;
}

I'd then use setInterval to count up to 1000, something like this:

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

The trick is to get it to happen in 3 seconds since the execution speed of javascript varies between browsers. The 10 millisecond delay and counting in jumps of 100 worked for me in FireFox and Google Chrome.

The code above will keep running every 10 milliseconds, but won't actually change anything once it exceeds $10,000. It can therefore will start counting up again as soon as you set x to something less than 10,000. However you can stop executing the code by using clearInterval(interval)

Adam
this looks nice and simple. Any way to reset it to run over and over without refreshing the page?
Wes
@Wes just set x back to 0. That'll reset it as I never called clearInterval
Adam
so at the end of the function put x = 0; ? Doesnt seem to work..
Wes
Ah, It was because of something else. worked..
Wes
Most browsers won't actually execute at 1 millisecond. Firefox will impose around a 10ms delay on intervals (or more). If you're looking for performance you should try comparing 1ms to 10ms and see which is faster. Also, -clear your interval-.
Mike Robinson
@Mike Very true. I set the interval to 10 milliseconds and didn't notice much difference in either Chrome or Firefox. I've edited my answer to mention clearing the interval as well.
Adam