[英]Increase by 1 every X seconds
I'm trying to write a code that counts something like how many people have been born in a country X since the beginning of 2016. I don't have much experience coding and this is what I've come out with. 我正在尝试编写一个代码,其中包括自2016年初以来X国出生了多少人。我没有太多的编码经验,这就是我的想法。 Where 'd' is now and 'b' are the milliseconds until the 1st of January 2016 in Unix time. 现在'd'是现在,'b'是直到Unix时间2016年1月1日为止的毫秒数。 My main problem is that when the page loads, the counter doesn't appear immediately but takes full 12 seconds to appear counting. 我的主要问题是,在页面加载时,计数器不会立即显示,而是需要整整12秒钟才能显示计数。
Is there a simpler way to do this and in which the numbers load immediately? 有没有更简单的方法可以做到这一点,数字可以立即加载? Thanks! 谢谢!
<span id="number"></span>
<script type="text/javascript">
var d = new Date();
document.getElementById('number').innerHTML = d.getTime();
var b = 1451606400000;
var i = ((d - b) / 12024);
var x = Math.round(i);
function increment() {
x++;
document.getElementById('number').innerHTML = x;
}
setInterval('increment()', 12024);
</script>
The problem is that increment
is not being called by setInterval
until the initial 12 second delay is reached, and your innerHTML
is not set until increment
is called. 问题在于,直到达到初始的12秒延迟, setInterval
才调用increment
,并且直到调用increment
之前, innerHTML
才被设置。
One solution would be to assign x
to innerHTML
once x
has a proper value... 一个解决办法是分配x
到innerHTML
一次x
有一个合适的值...
<script type="text/javascript">
var d = new Date();
var b = 1451606400000;
var i = ((d - b) / 12024);
var x = Math.round(i);
document.getElementById('number').innerHTML = x;
function increment() {
x++;
document.getElementById('number').innerHTML = x;
}
setInterval(increment, 12024);
</script>
Set x
instead of d
on initialization: 在初始化时设置x
而不是d
:
var d = new Date(); var b = 1451606400000; var i = ((d - b) / 12024); var x = Math.round(i); document.getElementById('number').innerHTML = x; // Here function increment() { x++; document.getElementById('number').innerHTML = x; } setInterval(increment, 12024);
<span id="number"></span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.