amrlabib / react-timer-hook

React timer hook
https://www.npmjs.com/package/react-timer-hook
MIT License
515 stars 112 forks source link

Ability to run the timer in smaller intervals (500ms) #35

Closed rafmsou closed 3 years ago

rafmsou commented 4 years ago

Hi,

I had a use case where I needed to run a timer in 1.5 seconds and saw that it was running every second because of the setInterval that is set to run each 1000ms.

I was wondering whether there is a reason not to support that? I could work on adding that myself.

Thanks!

amrlabib commented 4 years ago

Hi @rafmsou thank you for the issue, trying to understand your use case what do you mean by run a timer in 1.5 seconds ? you want to change the default interval from 1000ms (1s) to be 1500 (1.5s) ?

we can pass a custom param to change the default interval but just to confirm, this means that if the custom interval is 1.5s a 1 minute timer will run for (1.5s * 60) = 90s is this what you are trying to achieve ?

rafmsou commented 4 years ago

Hi @amrlabib , no, its not that. I'll try to give you a concrete example:

If you try to run a task in 1.5 seconds from now, it will actually run in 1 second from now. If you try to run a task in 500 milliseconds it will run in 1 second.

That's because the min interval in which tasks are checked is fixed in 1000ms (1 sec). So, any task that needs to run in a not rounded number of seconds will not get executed in the correct moment.

If you accept a custom parameter for the min interval, it will work, however there's more things that might need to change because some places assumes the number of seconds is round (or it gets rounded/floored).

I would say that the goal here would be to make it possible to run timers in intervals less than a second (100ms, 300ms, 500ms) accurately.

Does that makes sense?

vrgimael commented 4 years ago

Could we get milliseconds from the hook with minimal modification? That would solve the problem.

A "throttle" prop would be awesome though

amrlabib commented 3 years ago

Sorry for the late response, i updated the code of useTimer to handle milliseconds

Example: 1

if expiryTimeStamp will result in a 3.4 seconds [3400 ms] timer, it will behave as mentioned below: interval values
now 00:00:04
after 400 ms 00:00:03
after 1000 ms 00:00:02
after 1000 ms 00:00:01
after 1000 ms 00:00:00

Example: 2

if expiryTimeStamp will result in a 0.6 seconds [600 ms] timer, it will behave as mentioned below: interval values
now 00:00:01
after 600 ms 00:00:00

This is handled in v2.0.5, let me know if this is working well, and thank you again for reporting the issue

yoiang commented 3 years ago

Haha I have a similar request, except that I'd love to be able to get sub-seconds (milliseconds) from useStopwatch! Maybe by specifying an update interval...?

Happy to make a PR, just checking if you already know a quick change or any gotchas before I try my hand!