Home > Software engineering >  How can I make a counter keep increasing to a certain number on a specified date?
How can I make a counter keep increasing to a certain number on a specified date?

Time:12-18

I want to create a counter for my website that increases to a number, but reaches that number after a year.

For example, the counter starts at 0 and its target number is 35340340, so the counter should reach that number after one year has passed.

I've been trying and I can create an animated counter that takes 31,556,900,000 milliseconds to reach its target number, but it resets to 0 every time I load the page, so I don't know if it is possible to indicate a date as it is done with a downtimecounter, but do it with a counter that goes up and is not based on seconds and minutes.

CodePudding user response:

You know when you set the counter

So you can do this calculation each time you load

NOTE you need to consider timezones if it is important that the number is reached at a specific time

const targetNumber = 35340340;
const speed = 100; // milliseconds
const startDate = new Date(2021,11,16,15,0,0,0); // normalise at 15:00 - here yesterday
const aYearLater = new Date(startDate.getFullYear() 1,startDate.getMonth(),startDate.getDate(),15,0,0,0); 
const diffMS = aYearLater.getTime() - startDate.getTime(); // 365 or 366 in ms
const ticksPerMS = targetNumber/diffMS;
// console.log(ticksPerMS); 
const now = new Date();
const diffFromStart = now.getTime() - startDate.getTime();
let counterNow = (diffFromStart*ticksPerMS)
const counter = document.getElementById("counter");
setInterval(function() {
  counter.innerText = (counterNow  = (ticksPerMS*speed)).toFixed(2)
},speed)
<span id="counter"></span>

Update from your comment

const initialNumber = 99.990867579909;
const targetFinal = 100.000000000000;
const targetNumber = targetFinal - initialNumber;


const speed = 100; // milliseconds
const startDate = new Date(2021, 11, 16, 15, 0, 0, 0); // normalise at 15:00 - here yesterday
const aYearLater = new Date(startDate.getFullYear()   1, startDate.getMonth(), startDate.getDate(), 15, 0, 0, 0);
const diffMS = aYearLater.getTime() - startDate.getTime(); // 365 or 366 in ms
const ticksPerMS = targetNumber / diffMS;
// console.log(ticksPerMS); 
const now = new Date();
const diffFromStart = now.getTime() - startDate.getTime();
let counterNow = (diffFromStart * ticksPerMS)
const counter = document.getElementById("counter");
let tId = setInterval(function() {
  counter.innerText = (counterNow  = (ticksPerMS * speed)).toFixed(12)
  if (counterNow >= targetFinal) clearInterval(tId);
}, speed)
<span id="counter"></span>

  • Related