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. Where 'd' is now and 'b' are the milliseconds until the 1st of January 2016 in Unix time. My main problem is that when the page loads, the counter doesn't appear immediately but takes full 12 seconds to appear counting.
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.
One solution would be to assign x
to innerHTML
once x
has a proper value...
<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:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.