函数防抖(debounce)
概念:在事件被触发 n 秒后再执行回调,如果在这 n 秒内又被触发,则重新计时。
function debounce(fn, wait) { var timer = null; return function() { var context = this; var args = arguments; if (timer) { clearTimeout(timer); timer = null; } timer = setTimeout(function() { fn.apply(context, args); }, wait); }; }
函数节流 throttle
概念: 规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。
function throttle(fn, gapTime) { let _lastTime = null; return function() { let _nowTime = +new Date(); if (_nowTime - _lastTime > gapTime || !_lastTime) { fn(); _lastTime = _nowTime; } }; }