mirror of
https://github.com/vercel/streamdown.git
synced 2026-09-19 02:18:37 +08:00
52db013a3b
* Implement mode * Add tests * Create static test page * Split up code block files * Load static / streaming code block dynamically * Extract highlighting from highlight manager * Remove abort controller from static * Add static fallback * Split header * Update docs * Create soft-dragons-type.md * Fix tests
42 lines
1.1 KiB
TypeScript
42 lines
1.1 KiB
TypeScript
import { useEffect, useRef, useState } from "react";
|
|
|
|
export const useThrottledDebounce = <T>(
|
|
value: T,
|
|
throttleMs = 200,
|
|
debounceMs = 50
|
|
) => {
|
|
const [processedValue, setProcessedValue] = useState(value);
|
|
const lastRunTime = useRef(0);
|
|
const timeoutRef = useRef<number | null>(null);
|
|
|
|
useEffect(() => {
|
|
const now = Date.now();
|
|
const timeSinceLastRun = now - lastRunTime.current;
|
|
|
|
// Clear any pending debounce
|
|
if (timeoutRef.current) {
|
|
window.clearTimeout(timeoutRef.current);
|
|
}
|
|
|
|
// If enough time has passed, run immediately (throttle)
|
|
if (timeSinceLastRun >= throttleMs) {
|
|
setProcessedValue(value);
|
|
lastRunTime.current = now;
|
|
} else {
|
|
// Otherwise, debounce it
|
|
timeoutRef.current = window.setTimeout(() => {
|
|
setProcessedValue(value);
|
|
lastRunTime.current = Date.now();
|
|
}, debounceMs);
|
|
}
|
|
|
|
return () => {
|
|
if (timeoutRef.current) {
|
|
window.clearTimeout(timeoutRef.current);
|
|
}
|
|
};
|
|
}, [value, throttleMs, debounceMs]);
|
|
|
|
return processedValue;
|
|
};
|