Image stabilization
// Timer mode is implemented
export const debounce = (fn, delay) = >
const timer = null;
return (. param) = > {
if (timer) clearTimeout(timer);
timer = setTimeout(() = >{ fn(... param); }, delay); }; }Copy the code
// reactHook
export const useDebounce = (value, delay) = > {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() = > {
// Set a timer every time the value changes
const timer = setTimeout(() = > setDebouncedValue(value), delay);
// Run after the last useEffect
return () = > clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
};
Copy the code
/ / test
// You need to resize the window
window.onresize = debounce(() = > {
console.log(111);
}, 500);
Copy the code
The throttle
// Timer mode is implemented
export const throttle = (fn, delay) = >
const timer = null;
return (. params) = > {
if(! timer) { timer =setTimeout(() = >{ fn(... params); timer =null; }, delay); }}; }Copy the code
// Time stamp
export const throttle = (fn, delay) = >
const pre = 0;
return (. params) = > {
let now = new Date().getTime();
if (now - pre > delay) {
fn(...params);
pre = now;
}
};
}
Copy the code
/ / test
// You need to resize the window
window.onresize = throttle(() = > { console.log(111); }, 2000);
Copy the code