定义
防抖:事件触发n秒后再执行回调,如果在n秒内再次触发的话,就要重新计算时间。就是说事件什么时候不触发了,就在那个点的n秒后执行回调。
节流:n秒内只运行一次,若在n秒内重复触发,只有一次生效。
应用场景
使用高频事件调用函数
防抖:
页面滚动
搜索框当停止输入调用搜索函数
表单验证
按钮提交事件
浏览器缩放事件
节流:
DOM元素拖拽
搜索联想(keyup)
计算鼠标移动的距离
canvas模拟画板功能
监听滚动事件判断是否页面滚到底部自动加载更多
封装方法
防抖
function debounce(func, wait){
let timer = null;
return function() {
let _this = this;
let args = arguments;
if(timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(_this, args)
}, wait)
}
}
节流
function throttle(func, wait){
let timer = null;
return function() {
let _this = this;
let args = arguments;
if(!timer){
timer = setTimeout(() => {
timer = null;
func.apply(_this, args)
}, wait)
}
}
}