去抖
在一段时间内同一个时间触发了很多次,规定一定的时间 的多次点击事件延迟执行,最终只触发一次
// 250 毫秒内点击多次只有最后一次生效
var d = undefined
var debouncing = function(){
clearTimeout(d)
d = setTimeout(()=>{
console.log("do some ting")
},250)
}
相关方法
- Lodash
- debounce()
参考:https://www.lodashjs.com/docs/lodash.debounce#_debouncefunc-wait0-options
// 避免窗口在变动时出现昂贵的计算开销。
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
// 当点击时 `sendMail` 随后就被调用。
jQuery(element).on('click', _.debounce(sendMail, 300, {
'leading': true,
'trailing': false
}));
// 确保 `batchLog` 调用1次之后,1秒内会被触发。
var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
// 取消一个 trailing 的防抖动调用
jQuery(window).on('popstate', debounced.cancel);
节流
定期检查事件是否在 【这个时间段】中触发,如果触发次数超过【指定次数】就不执行。
相关方法
- Lodash
- throttle()
参考:https://www.lodashjs.com/docs/lodash.throttle#_throttlefunc-wait0-options
// 避免在滚动时过分的更新定位
jQuery(window).on('scroll', _.throttle(updatePosition, 100));
// 点击后就调用 `renewToken`,但5分钟内超过1次。
var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
jQuery(element).on('click', throttled);
// 取消一个 trailing 的节流调用。
jQuery(window).on('popstate', throttled.cancel);