JS counter continuously updating

。_饼干妹妹 提交于 2019-11-29 11:55:34

This took me quite a long time to answer since I had to create my own format currency function.

A live demo can be found here: http://jsfiddle.net/dm6LL/

The basic updating each second is very easy and will be done through JavaScript's setInterval command.

setInterval(function(){
    current += .158;
    update();
},1000);

The update() function you see in the above code is just a simple updater referencing an object with the amount id to put the formatted current amount into a div on the page.

function update() {
    amount.innerText = formatMoney(current);
}

Amount and current that you see in the update() function are predefined:

var amount = document.getElementById('amount');
var current = 138276343;

Then all that's left is my formatMoney() function which takes a number and converts it into a currency string.

function formatMoney(amount) {
    var dollars = Math.floor(amount).toString().split('');
    var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1];
    if(typeof cents == 'undefined'){
        cents = '00';
    }else if(cents.length == 1){
        cents = cents + '0';
    }
    var str = '';
    for(i=dollars.length-1; i>=0; i--){
        str += dollars.splice(0,1);
        if(i%3 == 0 && i != 0) str += ',';
    }
    return '$' + str + '.' + cents;
}​
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!