Closed drisabelles closed 1 year ago
Throttle com uso de hooks:
import { useState, useEffect } from 'react'; function useThrottle(value: string, delay?: number = 800): string { const [throttledValue, setThrottledValue] = useState(value); useEffect(() => { let timeout: NodeJS.Timeout; functon handleInputChange() { clearTimeout(timeout); timeout = setTimeout(() => { setThrottledValue(value); }, delay); }; handleInputChange(); return () => clearTimeout(timeout); }, [value, delay]); return throttledValue; }
Aplicar no input:
import { useState } from 'react'; import useThrottle from './useThrottle'; function MyComponent() { const [inputValue, setInputValue] = useState(''); const throttledValue = useThrottle(inputValue); return ( <div> <input type="text" value={inputValue} onChange={(event) => setInputValue(event.target.value)} /> <p>Throttled value: {throttledValue}</p> </div> ); }
Exemplo de throttle encontrado/aprimorado:
function useThrottle<F extends (...args: any[]) => any>(func: F, waitFor?: number = 800) { let timeout: number; let startTime: number = Date.now() - waitFor; function resetStartTime() { startTime = Date.now(); }; return (...args: Parameters<F>): Promise<ReturnType<F>> => { const timeLeft = (startTime + waitFor) - Date.now(); if (timeout) clearTimeout(timeout); if (timeLeft <= 0) { resetStartTime(); return Promise.resolve(func(...args)); } else { return new Promise((resolve) => { timeout = setTimeout(() => { resetStartTime(); resolve(func(...args)); }, timeLeft); }); } }; } // usage useThrottle((hello: string) => { console.log(new Date().getTime(), '>>>', hello) });
Throttle com uso de hooks:
Aplicar no input:
Exemplo de throttle encontrado/aprimorado: