防抖动与节流
DEMO
防抖动
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 27 28
| var debounce = function (fn, delay, isImmediate) { var timer = null; isImmediate = typeof isImmediate === "undefined" ? false : isImmediate;
return function () { var ctx = this, args = arguments; if (timer) { clearTimeout(timer); } if (isImmediate) { if (!timer) { fn.apply(ctx, args); } timer = setTimeout(_ => { timer = null; }, delay); } else { timer = setTimeout(_ => { fn.apply(ctx, args); }, delay); } }; };
|
防抖动立即触发
防抖动
节流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| var throttle = function (fn, delay, isImmediate) { var timer = null; isImmediate = typeof isImmediate === "undefined" ? true : isImmediate;
return function () { var ctx = this, args = arguments; if (!timer) { if (isImmediate) fn.apply(ctx, args); timer = setTimeout(function () { clearTimeout(timer); timer = null; if (!isImmediate) fn.apply(ctx, args); }, delay); } }; };
|
节流立即触发
节流
总结
- 防抖动:将多个操作合并为一个操作(例如,键盘输入关键字搜索内容),在规定延时时间后触发,如果在定时器时间范围内触发,则会清楚定时器,重新计时
- 节流:在给定的延时时间后触发一次操作,在此时间范围内的操作均不触发(例如,图片懒加载、向下无限滚动获取新数据)
Last updated: