JS counter continuously updating
嘿,首先:我是编码新手,我是一名学生,我在这方面一直很挣扎,所以我认为终于是时候问别人了。所以我一直在看this question并且它在 html 中完美运行。但是我想从终端运行它(我使用节点来执行文件)。 我已经尝试为此修改代码。但计算似乎不行。它打印:£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);
我完全没有想法,所以我非常感谢任何形式的帮助。谢谢!
最佳答案
为什么要尝试在更新函数中设置 amount.innertext 而不仅仅是 amount?当您使用 amount 而不是 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);
关于Javascript 计数器以从终端运行的特定速率不断更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43597609/