Home > Enterprise >  Count down with setInterval has time difference
Count down with setInterval has time difference

Time:10-29

let count = 60;

function timeLeft(){
    count = count - 1;
    if(count == 0){
        count = 60;
    }
}

setInterval(() => timeLeft(), 1000)
setInterval(() => machoAirline.changePrice(), 60000);
setInterval(() => yenoTech.changePrice(), 60000);

This code is the countdown for showing how much time is left until stocks' prices change. But after some minutes, there is a gap between counter and prices update.

console:

price updated!
counter: 42

What's the problem?

CodePudding user response:

Timeout and intervals may take longer to fire when you want due to:

  • inactive of tabs
  • throttling of tracking scripts
  • Late timeouts because browser busy with other tasks.

If you need correct order of machoAirline and yenoTech execution you can combine them in one setInterval:

setInterval(() => {
  machoAirline.changePrice();
  yenoTech.changePrice();
}, 60000);

CodePudding user response:

setInterval does not keep accurate time, as described in other answers. This means that calculating elapsed time by counting the invocations of setInterval will result in inaccurate timings when compared to wall-time (or indeed, other intervals that you have set).

performance.now() is the most accurate measure of time available in the browser.

If timing is critical, then consider polling performance.now() in the body of a setInterval callback that runs at a short interval...

Something like:

const now = performance.now();
const finishTime = now   3000; // 3s time

const handle = setInterval(() => {
  if (performance.now() >= finishTime) {
    console.log("some action");
    clearInterval(handle); // kill the timer
  }
}, 100); // poll every 100ms (ish)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related