0
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?

Nyaco
  • 1
  • 1
    What is `machoAirline` and `yenoTech`? – Geuis Oct 29 '21 at 01:55
  • What is the result you expect – Maxpan Oct 29 '21 at 02:01
  • The problem is that you're misuing `setInterval()` and expecting it to keep accurate time and it is not designed to do that. `setInterval()` intervals are approximate only. Look at the wall time when the interval is called if you want to know the real time elapsed. – jfriend00 Oct 29 '21 at 02:29

2 Answers2

0

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);
marvinav
  • 667
  • 5
  • 15
0

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)
spender
  • 117,338
  • 33
  • 229
  • 351