手写节流防抖函数
因为整体并不复杂,直接上代码理解就可以了。
节流(throttle)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| const throttle1 = (fn, time) => { let flag = false; return (...args) => { if (flag) return; fn.call(undefined, ...args); flag = true; setTimeout(() => { flag = false; }, time); }; };
const throttle2 = (fn, time) => { let timer = null; return (...args) => { if (timer) { return; } fn.call(undefined, ...args); timer = setTimeout(() => { timer = null; }, time); }; };
|
防抖(debounce)
| const debounce = (fn, time) => { let timer = null; return (...args) => { if (timer !== null) { clearTimeout(timer); } timer = setTimeout(() => { fn.call(undefined, ...args); timer = null; }, time); }; };
|
如需立即执行再加一个参数即可。