- 防抖和节流都是一种优化技术,用来降低函数的调用频率,提高性能
防抖(Debouncing)
- 在连续触发某个事件时,只有当一定时间内没有再次触发时间,才会执行事件处理函数。比如说:我们需要监听用户输入框中的文字,只有用户停止输入一段时间采取发送请求获取数据
/**
* 防抖函数
*
* @param func 回调函数
* @param delay 延迟时间
* @returns {(function(...[*]): void)|*}
*/
const debounce = (func, delay) => {
let timeoutId = null
return function (...arguments) {
// this
const context = this;
// 传递的参数
const args = arguments;
// 清除定时器
timeoutId && clearTimeout(timeoutId);
// 延迟执行函数
timeoutId = setTimeout(function () {
func.apply(context, args);
}, delay);
}
}
- 使用 防抖函数
// 调用防抖函数
const DebounceFn = debounce(function () {
console.log("debounce我被执行了")
}, 2000)
Debounce()
应用场景:
- 实时搜索
- 拖拽
节流(Throttling)
- 节流的主要思想是在一系列连续的触发事件中,按照一定的时间间隔执行函数。即,在规定的时间内,无论触发事件多少次,只执行一次函数
/**
* 节流函数
*
* @param func 回调函数
* @param delay 延迟时间
* @returns {(function(...[*]): void)|*}
*/
function throttling(func, delay) {
let timeoutId = null
return function (...arguments) {
if(!timeoutId){
// this
const context = this;
// 传递的参数
const args = arguments;
timeoutId = setTimeout(function (){
func.apply(context, args);
timeoutId = null
}, delay)
}
}
}
- 使用 节流函数
const ThrottlingFn = throttling(function(){
console.log("throttling我被执行了")
}, 2000)
应用场景:
- 窗口调整
- 页面滚动
- 抢购疯狂点击