Home > Software engineering >  JS Counter that increase each day from base number
JS Counter that increase each day from base number

Time:09-08

I want to create a counter that starts at 1000 and increases by 40 every 24 hours.

I can't seem to find this in any other SO posts, could someone please help?

Thanks.

CodePudding user response:

let count = 1000;
let delay = 24 * 3600000; // 1 hour equal to 3.600.000 ms

const timer = setInterval(() => {
  count  = 24;
  console.log(count);
}, delay)

const clearTimer = () => {
  clearInterval(timer)
} // if u want to stop interval;

CodePudding user response:

This counter will start from 1000 then add 40 every 24 hours. you can change the values and time as you wish. you can change time value to 1000 which = 1 sec to see how it works.

var resultDisplay = document.getElementById("result");

var baseNum = 1000;
var add = 40;
var time = 24 * 3600000; // change the 24 to any hours you want

resultDisplay.innerHTML = baseNum;

function add40() {

    setTimeout(() => {
        resultDisplay.innerHTML = baseNum;

        if (baseNum !== 0) {
            baseNum  = 40;
        } add40()
    }, time);
} add40();
 <div  id="baseNum"> base number = 1000</div>
   <div  id="resultContainer">
    after every 24 hours   40 = <span  id="result"></span>
  </div>

CodePudding user response:

Try this:

let count = 1000;
const intervalPeriod = 86400000;  // 24 hours in milliseconds

const timer = setInterval(() => {

count  = 40 // increment by 40
console.log("After increment", count)
}, intervalPeriod)

//   clearInterval(timer) if you want to clear interval

CodePudding user response:

The previous answers all rely on the script running continuously over several days. They also completely ingnore the notion of daylight saving times and different time zones.

Here is an alternative solution, based on shyam's idea for calculating a reliable date difference:

function utcdate(d){
  return new Date(d.getFullYear(),d.getMonth(),d.getDate());
}
function days(a,b){
 return Math.floor((utcdate(b)-utcdate(a))/86400000);
}

// define starting count and a start date:
const count=1000, date0=new Date(2022,8,1); // 1 September 2022

console.log(1000   40*days(date0,new Date()));

This approach will work reliably - delivering the same result everywhere in the world - and it is also does not require an app to be constantly running. The calculation is based on the UTC dates of each given (local) date. This makes it agnostic to time zones and any locally applicable daylight saving times.

  • Related