防抖
防抖是让一个函数在一段时间间隔内没有调用,才开始执行被调用
function debounce(func, delay){// set timer as nulllet timer = null;return function() {// if timer is not null, wipe it// if you input a value during the timer, wipe the last time// and start to time againif(timer) clearTimeout(timer)timer = setTimeout(() => {// change the direction of thisfunc.call(this)}, delay)}}// React hooks 版本const useDebounce = (func: any, delay: number) => {const timer = React.useRef<any>(null);const debounce = React.useCallback(() => {if(timer.current) clearTimeout(timer.current)timer.current = setTimeout(() => {func();}, delay)}, [func, delay])return debounce;}
节流
节流是让一个函数无法在很短的时间间隔内被多次调用。意思就是一个函数被调用了后,得让它歇一下,等它歇完了(等一定的时间间隔之后),才能被再次调用。
function throttle(func, delay){let previous = 0return function() {let now = Date.now()if(now-previous > delay){func.call(this)previous = now}}}// react hooks functionconst useThorttle = (func: any, delay: number) => {const timer = React.useRef<any>(-1)const throttle = React.useCallback(() => {if(timer.current > -1) return null;timer.current = setTimeout(() => {func();timer.current = -1;clearTimeout(timer.current);}, delay)}, [func, delay])return throttle}
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><input type="text"><div style="height: 1000px;"></div></body><script>const input = document.querySelector('input');input.oninput = debounce(function () {console.log(this.value);}, 1000)function debounce(func, delay) {let timer = nullreturn function () {if (timer) clearTimeout(timer)timer = setTimeout(() => {func.call(this)}, delay)}}window.onscroll = throttle(function () {console.log('page scroll');}, 1000);// window.onscroll = function () {// console.log('page scroll');// };function throttle(func, delay) {let previous = 0;return function () {let now = Date.now();if (now - previous > delay) {func.call(this);previous = now;}}}</script></html>
