From 5b590cdd4799c9274158e58aeb982f714ec7436d Mon Sep 17 00:00:00 2001 From: Tilman Vatteroth Date: Mon, 17 Jul 2023 17:52:18 +0200 Subject: [PATCH] wip Signed-off-by: Tilman Vatteroth --- .../src/hooks/common/use-deferred-state.ts | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/frontend/src/hooks/common/use-deferred-state.ts b/frontend/src/hooks/common/use-deferred-state.ts index df27305b8..5e70a8873 100644 --- a/frontend/src/hooks/common/use-deferred-state.ts +++ b/frontend/src/hooks/common/use-deferred-state.ts @@ -7,32 +7,39 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { useInterval } from 'react-use' +const minimumTimeBetweenUpdateInterval = 200 +const forceUpdateAfterTime = 1000 + /** * Takes a value that changes often and outputs the last value that hasn't been changed in the last interval. * * @param value The value to defer * @param initialValue The initial value that is used until the first update - * @param checkInterval The interval in ms that is used to check for updates. Default is 200ms. * @return The slowed down value */ -export const useDeferredState = (value: T, initialValue: T, checkInterval = 200): T => { +export const useDeferredState = (value: T, initialValue: T): T => { const valueRef = useRef(initialValue) - const lastTimestamp = useRef(0) + const lastIncomingUpdateTimestamp = useRef(0) + const lastOutgoingUpdateTimestamp = useRef(0) const [deferredValue, setDeferredValue] = useState(initialValue) useEffect(() => { valueRef.current = value - lastTimestamp.current = new Date().getTime() + lastIncomingUpdateTimestamp.current = new Date().getTime() }, [value]) useInterval( useCallback(() => { const currentTimeStamp = new Date().getTime() - if (currentTimeStamp - lastTimestamp.current >= checkInterval) { + if ( + currentTimeStamp - lastIncomingUpdateTimestamp.current >= minimumTimeBetweenUpdateInterval || + currentTimeStamp - lastOutgoingUpdateTimestamp.current >= forceUpdateAfterTime + ) { + lastOutgoingUpdateTimestamp.current = currentTimeStamp setDeferredValue(valueRef.current) } - }, [checkInterval]), - checkInterval + }, []), + 100 ) return deferredValue