talalmajali / react-native-countdown-component

React Native CountDown
MIT License
266 stars 233 forks source link

2 seconds left at the end of 1 min timer #51

Open sudhirkumarojhaa opened 5 years ago

sudhirkumarojhaa commented 5 years ago

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

dane-du-plessis commented 3 years ago

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.

mehthabux commented 3 years ago

any luck ?

Calquito commented 3 years ago

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 commented 3 years ago

any luck ?

hope this helps