1

I'm developping an ionic app.

I create a counter with setInterval.

let test = new Date().getTime();
setInterval(() => {

  console.log(new Date().getTime() - test);
  test = new Date().getTime();
}, 1000);

Problem, the console.log give not the answer 1000. It is completely random and sometimes more thant 3000.

Have you an idea why is it so?

anubis
  • 1,425
  • 5
  • 18
  • 47
  • 4
    There's no guarantee of accuracy with browser timers. They're usually pretty close. If your tab loses focus the browser will slow them way down. – Pointy Jan 11 '18 at 14:53
  • setInterval only guarantees that the callback will be called at least n milliseconds later. So, if there are a lot of events in the callback queue, they will all have to finish before the setInterval callback is called. – Brian Jan 11 '18 at 14:55
  • https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Reasons_for_delays_longer_than_specified – Teemu Jan 11 '18 at 14:56

1 Answers1

0

There is no way to guarantee the exact time because even the simplest function like this it takes some millisecond to execute the content inside the interval function. setInterval function only guarantee the time interval.

Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80