I am currently implementing a nodejs countdown timer.
I have a client who requests for the remaining time that the server maintains(timer), and client also has a countdown timer too.
Upon implementing client-side countdown timer, I've read many articles and suggestions that we should never use setInterval
in the browser, since it could be inaccurate. so I am using react-countdown for measuring accurate countdown.
So I also tried to search in which approach is the best to implement nodejs countdown timer too. But many answers in stackoverflow suggest to use setInterval
.
Is it pretty accurate to use setInterval in nodejs side?
appreciate in advance for your help.
setInterval()
, like setTimeout()
, doesn't guarantee accurate timing. It guarantees minimum timing. The callback is invoked after the given delay. But it might be invoked a while after the delay. If you assume setInterval()
is calling your function right on time you'll end up with clock that runs slow.
You can still build a timer using setInterval()
. But don't use the delay for timing, use it as the polling interval and instead check the system clock.
Like this:
const seconds = () => Math.floor(Date.now()/1000)
let then = seconds()
const started = then
function timer() {
const now = seconds()
if (then != now) { // We're in a new second.
console.log(now-started)
then = now
}
}
setInterval(timer, 100)
The timer()
function runs 10 times per second. The console.log()
inside the function runs once each second.
But this only happens approximately. In normal conditions it'll take a little over 1000ms to display the next tick with the occasional 900ms catchup. But it can easily take much longer — even many seconds — depending on what else is happening in your code (or on the system).
As an example, put this line after the code above:
setTimeout(() => {while(seconds()-started < 5) {}}, 2000)
It'll block Node's event loop until the conditional turns false. As setInterval()
depends on the event loop, timer()
misses a bunch of seconds. While this is an arbitrary example, it's not uncommon for the event loop to be delayed while other things are going on.
In general there is no mechanism to guarantee timer accuracy within Node.js. Or, for that matter, any programming system running on "regular" Linux, Windows, MacOS, etc. For that sort of functionality you need to run an RTOS and even then there are substantial caveats.
But that's a pretty rare need. For plenty of applications setInterval()
is more than adequate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With