usehooks
usehooks copied to clipboard
Fix useThrottle timing
This fixes a couple issues that lead to subtle timing bugs in useThrottle. For an example, see this codesandbox and notice how throttledValue (current implementation) updates kind of choppily and drops some values, whereas throttledValue2 (includes this fix) works as you'd expect.
First fix is that the now
variable inside setTimeout
does not actually refer to the current time, it refers to the time setTimeout
was called. That means lastUpdated.current
will be incorrect (too low) for the next update. Instead we should get a new Date.now()
value.
Second fix is that the setTimeout
is currently delayed by the full value of interval
, even if there is only like a millisecond left until the interval elapses. Fix is to instead delay it by interval
minus the time since the last update.