0

I am trying to understand this piece of code but I get different results in different runtime environment: The condition:

  1. Print "Hello World" Every second
  2. And stop after 5 times
  3. After 5 times. Print "Done" and let Node exit.

let timerId = setInterval(() => console.log("Hello world"), 1000);

// after 5 seconds stop
setTimeout(() => {
  clearInterval(timerId);
  console.log("Done");
}, 5000);

In Node.js, this is printed in terminal:

enter image description here

The message is printed 4 times, not 5 times!

In browser's console, it is fine:

enter image description here

But when I add debugger to the code and run in browser, I get a completely different result: enter image description here

Any clarification is appreciated, thank you

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Nader.Bhr
  • 53
  • 4

1 Answers1

0

There’s a host of question/answers on this out there. See for example How to create an accurate timer in javascript? which discusses trying to create an accurate timer using setInterval and setTimeout.

Why is it not accurate? Because you are using setTimeout() or setInterval(). They cannot be trusted, there are no accuracy guarantees for them. They are allowed to lag arbitrarily, and they do not keep a constant pace but tend to drift (as you have observed).

You are at the mercy of a lot of factors, not least what else is going on at the same time.

A Haworth
  • 30,908
  • 4
  • 11
  • 14
  • Could someone explain why this has been down voted? Is it inaccurate, ie are setInterval and setTimeout accurate? No they are not. – A Haworth Oct 15 '20 at 16:03