定义:多次触发事件后,事件处理函数只执行一次,并且在触发操作结束时执行,一般用于scroll事件
原理:对处理函数进行延时操作,若设定的延时到来之前再次触发事件,则清除上一次的延时操作定时器,重新定时
let timer;
window.onscroll = function(){
if(timer){
clearTimeout(timer)
}
timer = setTimeout( function(){
//滚动条位置
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log('滚动条位置:' + scrollTop);
timer = undefined;
}, 200)
}
防抖与节流的区别
防抖动是将多次执行变为最后一次执行
,节流是将多次执行变成每隔一段时间执行
防抖:指定时间内只执行一次,但在等待时间内再次触发事件,重新开始延时。
防抖应用场景 – 搜索功能
,实时响应用户输入,给出相关的建议词。
//事件处理函数
function handle(arg){
//事件处理代码
console.log('事件处理函数-'+arg); //事件处理函数-keydownArg
}
//防抖
function debounce(fn, delay){
let timer = null;
return function(){
let content = this;
let args = arguments;
if(timer) clearTimeout(timer)
timer = setTimeout(function(){
fn.apply(content, args);
}, delay)
}
}
//事件绑定
var input = document.getElementById("input");
input.onkeydown = debounce(function(){
handle('keydownArg')
}, 500)
节流:指定时间内只执行一次。
节流应用场景 – 窗口大小
改变,下拉加载
等。
//事件处理函数
function handle(){
// 事件处理代码
console.log('事件处理函数-'+arg); //事件处理函数-resizeArg
}
// 防抖处理
function throttle(fn, delay){
let timer = null;
return function(){
if(timer) return false;
let content = this;
let args = arguments;
timer = setTimeout(function(){
timer = null
fn.apply(content, args);
}, delay)
}
}
//事件绑定函数
window.onresize = throttle(function(){
handle('resizeArg')
}, 500)