https://www.html.cn/archives/6589/
throttle节流
一个函数在大于设定的执行周期后,才会再次执行
- 性能能优化角度,在规定的时间内,函数第一次执行有效,后面的无效
第一次有效
Button的疯狂点击,例如秒杀的抢购
- resize窗口调整
- scroll 页面滚动
- DOM的拖拽功能
函数节流用 Date.now实现,求时间差值
throttle(callback, wait)
export function throttle(callback, timeout) {
let startTime = 0;
return (...args) => {
let nowTime = Date.now();
// 第一次会执行,后面 startTime = nowTime
if(nowTime - startTime >= timeout) {
callback.call(this, ...args);
startTime = nowTime;
}
}
}
节流函数,在 wait 毫秒内最多执行 callback 一次
debounce防抖
频繁触发事件,在规定的时间内,只会执行最后一次,前面的不执行
- 最后一次有效
- input
- scroll
- keyup, keydown, keypress
函数防抖,用定时器实现
debounce(callback, wait)
debounce(() => {}, 1000)
export function debounce(callback, timeout = 500) {
let timer = null;
return (...args) => {
if(timer !== null) clearTimeout(timer);
timer = setTimeout(() => {
callback.call(this, ...args);
timer = null; // 执行完之后,重置timer
}, timeout);
}
}
防抖函数会从上一次被调用后,延迟 wait 毫秒后调用 callback