0

I need to run a job every second in node.js. First I tried to use setInterval, then I tried later.js https://www.npmjs.com/package/later

But when I try to run my job with both of these ways, I have the same problem: there is a lag in about 2-3 milliseconds.

I placed console.log(new Date()) in my job and it shows that every next calling of my job happens 2-3 milliseconds later than the previous one.

What is the best and precise way of running a job every second in node.js?

Stas Coder
  • 309
  • 5
  • 10
  • Use `setTimeout()` instead, and at the end of the task check the clock and schedule the next one. That said, getting a timer to go off within 2 to 3 milliseconds of when you want it is probably about the best you can expect. – Pointy Oct 17 '17 at 14:12
  • @Pointy maybe there is some library for that? I searched a long time for that, but cant find a goob lib for that problem. – Stas Coder Oct 17 '17 at 14:15
  • https://www.npmjs.com/search?q=precision+timer – robertklep Oct 17 '17 at 14:15
  • 1
    If your code isn't running on a real-time OS, there's only so much that Node can do. – Pointy Oct 17 '17 at 14:17
  • @robertklep unfortunately among offered libs there is no suitable one. – Stas Coder Oct 17 '17 at 14:18
  • @StasCoder why not? – robertklep Oct 17 '17 at 14:19
  • Most of the libraries found by @robertklep are for time measurement, not for event timing. The rest are either web-based, or fall back to the JS engine and use math to adjust for "drift". The core problem is that JS engines run in an event loop, and there's no "interrupt handling" available. Callbacks are only called "between" event loops. It might be possible to build a native library to do the job, but I'd only give it a 50/50 chance. – theGleep Oct 17 '17 at 14:25
  • [`rolex`](https://www.npmjs.com/package/rolex) offers an interval timer with drift limiting that outperforms `setInterval`. I think it's as good as you're going to get (with _any_ interpreted language, possibly). – robertklep Oct 17 '17 at 14:28
  • the best solution I found is https://gist.github.com/manast/1185904 – Stas Coder Oct 17 '17 at 14:54
  • I think you can use the solution here https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript – Van Hung Dec 01 '21 at 07:18

0 Answers0