react-native-countdown-component icon indicating copy to clipboard operation
react-native-countdown-component copied to clipboard

2 seconds left at the end of 1 min timer

Open sudhirkumarojhaa opened this issue 5 years ago • 4 comments

The timer is working fine when the timer finishes after 1 minute but the output is 2 seconds left. Please tell me the solution.

sudhirkumarojhaa avatar Jul 18 '19 07:07 sudhirkumarojhaa

This is a serious problem. This component will not function as a precise timer. If your application requires accurate timekeeping, do not use it.

It uses the JavaScript setInterval function, which includes the time taken to compute your function in the interval. It should instead be using setTimeout, which does not. See the code.

Depending on your code, there will be drift between an accurate clock and the timer, enough to notice after just a few seconds.

I wrote another timing component which uses setTimeout, which solves the problem. See the MDN documentation for these functions, which says:

Recursive setTimeout() guarantees the same delay between the executions. (For example, 100ms in the above case.) The code will run, then wait 100 milliseconds before it runs again—so the interval will be the same, regardless of how long the code takes to run. The example using setInterval() does things somewhat differently. The interval you chose includes the time taken to execute the code you want to run in. Let's say that the code takes 40 milliseconds to run — the interval then ends up being only 60 milliseconds.

I might submit a PR for better timing precision... if anyone else needs it?

EDIT: If you're trying to use setTimeout in React Native, be careful - I'm not convinced that it provides accurate time! Use Date.now() to get the actual system clock time and adjust the setTimeout milliseconds accordingly.

dane-du-plessis avatar Jul 28 '20 14:07 dane-du-plessis

any luck ?

mehthabux avatar Dec 01 '20 10:12 mehthabux

Based on https://github.com/klyngbaek/accurate-interval/blob/master/index.js i modified index.js to create this more accurate countdown:

accurate-countdown.zip

I have not measured its accuracy thoroughly, but it seems to have an uncertainty of miliseconds, a lot better than using setInterval()

Calquito avatar Jul 09 '21 02:07 Calquito

any luck ?

hope this helps

Calquito avatar Jul 14 '21 14:07 Calquito