I want to create a javascript live countdown. Almost like statistics site has. enter image description here
I have created the html file but I am not good at javascript so I need your help.
<table>
<tbody><tr><td class="counter"><div id="cp1">7,795,022,199</div></td>
<td class="data_name"><b>Current population</b></td></tr>
<tr><td class="counter"><div id="cp2">3,931,870,264</div></td>
<td class="data_name">Current male population <span id="cp4">(50.4%)</span></td></tr>
<tr><td class="counter"><div id="cp3">3,863,151,936</div></td>
<td class="data_name">Current female population <span id="cp5">(49.6%)</span></td></tr>
<tr><td class="counter"><div id="cp6">52,128,438</div></td>
<td class="data_name">Births year to date</td></tr>
<tr><td class="counter"><div id="cp7">406,110</div></td>
<td class="data_name">Births today</td></tr>
<tr><td class="counter"><div id="cp8">20,311,076</div></td>
<td class="data_name">Deaths year to date</td></tr>
<tr><td class="counter"><div id="cp9">158,235</div></td>
<td class="data_name">Deaths today</td></tr>
<tr><td class="counter"><div id="cp10">0</div></td>
<td class="data_name">Net migration year to date</td></tr>
<tr><td class="counter"><div id="cp11">0</div></td>
<td class="data_name">Net migration today</td></tr>
<tr><td class="counter"><div id="cp12">31,817,362</div></td>
<td class="data_name">Population growth year to date</td></tr>
<tr><td class="counter"><div id="cp13">247,875</div></td>
<td class="data_name">Population growth today</td></tr>
</tbody></table>
I need to set an interval and the number will be counting automatically. Such as one second. How can I do that? I want to use this in my WordPress blog.
Let's assume that you have a count
function
. In that case, you can execute that function
once per second with
setInterval(count, 1000);
Now, you need to define count
, like this:
function count() {
var items = document.querySelectorAll(".counter > div");
for (let item of items) item.innerText = (parseInt(item.innerText.replace(/,/g, '')) - 1).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
EDIT
If you want to do them in separate intervals, then you can do something of the like
function count(item) {
item.innerText = (parseInt(item.innerText.replace(/,/g, '')) - 1).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
and then
setInterval(function() {
count(document.getElementById("cp1"));
}, 1000);
setInterval(function() {
count(document.getElementById("cp2"));
}, 6000);
You can of course use your own logic to define times, the code above is just an illustration.