0

JS counter continuously updating

Hey, first of all: I'm a newbie to coding, I'm a student and I've been struggling so much with this bit that I thought it's finally time to ask someone else. So I've been looking at this question and it works perfectly in html. However I want to run it from the terminal (I'm using node to execute the file). I've tried to modify the code for that. But the calculation doesn't seem to work. It prints: £NaN.00

//counter
var amount = formatMoney(amount);
var startDate = new Date(2012, 07, 21);
var currentDate = new Date();
var seconds = (startDate - currentDate) / 1000;
var modifier = seconds * .158;
var current = 138276343 + modifier;

update();

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

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

function formatMoney(amount) {
    var pounds = 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=pounds.length-1; i>=0; i--){
        str += pounds.splice(0,1);
        if(i%3 == 0 && i != 0) str += ',';
    }
    return '£' + str + '.' + cents;
}

console.log(amount);

I'm completely out of ideas, so I would really appreciate any kind of help. Thanks!

Community
  • 1
  • 1
  • From the linked Answer - var amount = document.getElementById('amount'); _not_ var amount = formatMoney(amount); – muttonUp Apr 25 '17 at 00:23

1 Answers1

1

Why are you trying to set amount.innertext in your update function and not just amount? Works when you use amount instead of amount.innertext.

//counter
var amount = formatMoney(amount);
var startDate = new Date(2012, 07, 21);
var currentDate = new Date();
var seconds = (startDate - currentDate) / 1000;
var modifier = seconds * .158;
var current = 138276343 + modifier;
update();
function update() {
    amount = formatMoney(current);
}
setInterval(function(){
    current += .158;
    update();
},1000);
function formatMoney(amount) {
    var pounds = 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=pounds.length-1; i>=0; i--) {
        str += pounds.splice(0,1);
        if(i%3 == 0 && i != 0) {
            str += ",";
        }
    }
    return '£' + str + '.' + cents;
}
console.log(amount);
Ken
  • 466
  • 2
  • 7
  • Oh wow, thank you so much! That was why it said NaN as well, I had been wondering how it didn't recognise it as a number but obviously innerText is where I went wrong. Thanks! – Marie Ella Apr 25 '17 at 10:38