From 1cfe85c1407ab6daa760867c2eae400a6ab468c5 Mon Sep 17 00:00:00 2001 From: Jeremy Scheff Date: Thu, 2 May 2024 19:30:05 -0400 Subject: [PATCH] Fix useThrottle timing --- index.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index f6e4fe2..4aaf445 100644 --- a/index.js +++ b/index.js @@ -1240,19 +1240,20 @@ export function useSet(values) { export function useThrottle(value, interval = 500) { const [throttledValue, setThrottledValue] = React.useState(value); - const lastUpdated = React.useRef(null); + const lastUpdated = React.useRef(0); React.useEffect(() => { const now = Date.now(); + const sinceLastUpdate = now - lastUpdated.current; if (lastUpdated.current && now >= lastUpdated.current + interval) { lastUpdated.current = now; setThrottledValue(value); } else { const id = window.setTimeout(() => { - lastUpdated.current = now; + lastUpdated.current = Date.now(); setThrottledValue(value); - }, interval); + }, interval - sinceLastUpdate); return () => window.clearTimeout(id); }