gpt4 book ai didi

javascript - 将逗号添加到 setinterval 计数器值

转载 作者:行者123 更新时间:2023-11-29 21:50:09 26 4
gpt4 key购买 nike

标题可能不对,抱歉。

我正在尝试为一个网站制作一个实时计数器,它的想法是显示一个每秒都在增加的假数字。到目前为止我有这个

var START_DATE = new Date("November 27, 2014 13:30"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 901; // initial value when it's the start date
var count = 0; //finally this shit is working

window.onload = function()
{
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = count;
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = count;", msInterval);
}
<div id="counter"></div>

它显示每秒增加的数字,如“24350919”,我想将其转换为 24,350,919。我尝试使用 parseFloat,但我无法让它工作。

有人可以帮助我吗?谢谢!

最佳答案

编辑:-

var START_DATE = new Date("November 27, 2014 13:30"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 901; // initial value when it's the start date
var count = 0; //finally this shit is working


window.onload = function() {
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = addCommas(count);
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = addCommas(count);", msInterval);
}

function addCommas(myStr)
{
myStr += '';
var x = myStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
<div id="counter"></div>


您可以像这样尝试使用 toLocaleString():

var n = 24350919
n.toLocaleString()

在你的情况下它就像

setInterval("count += INCREMENT; document.getElementById('counter').innerHTML =
count;", msInterval.toLocaleString());

关于javascript - 将逗号添加到 setinterval 计数器值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29702042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com