前端高频面试题:
防抖和节流的理解,及其应用场景
01
概 念
区别: 函数节流不管事件触发有多频繁,都会保证在规定时间内一定会执行一次真正的事件处理函数,而函数防抖只是在最后一次事件后才触发一次函数。
比如在页面的无限加载场景下,我们需要用户在滚动页面时,每隔一段时间发一次 Ajax 请求,而不是在用户停下滚动页面操作时才去请求数据。这样的场景,就适合用节流技术来实现。
( 简要回答 )
防抖:防止抖动,单位时间内事件触发会被重置,避免事件被误伤触发多次。代码实现重在清零
节流:控制流量,单位时间内事件只能触发一次,如果服务器端的限流即 Rate Limit。代码实现重在开锁关锁
02
应用场景
连续的事件,只需触发一次回调的场景有:
间隔一段时间执行一次回调的场景有:
03
防抖的实现
防抖函数(普通)
var timer; //全局的timer,只有一个
function debounce(fn,delay){
if(timer){
clearTimeout(timer) //保证只开启一个定时器
}
timer = setTimeout(function(){
fn(); //延迟delay,执行函数
},delay)
}
window.onscroll = function(){
debounce(test,1000)
}
function test(){
console.log('滚动停')
}
需要将timer封装到debounce中,如果调用的fn有参数需要处理
function debounce(fn,delay){
let timer;
return function(){
let _this = this; //为了改写参数 保存this 应用apply
let _args = arguments; //保存testDebounceFn的入参
if(timer){
clearTimeout(timer);
}
timer = setTimeout(function(){
//apply传参正好和arguments匹配
fn.apply(_this,_args)
},delay)
}
}
let testDebounceFn = debounce(test,1000);
function test(a){
console.log('滚动停 '+a)
}
window.onscroll = function(){
testDebounceFn('aaaa')
}
04
节流的实现
节流(2种方式setTimeout 或者 new Date()) 防抖比节流严格,防抖在一定时间操作后只执行一次。节流在一定时间操作,可每隔n秒执行一次
setTimeout方式
function throttle(fn,delay){
let timer;
return function(){
let _args = arguments;
let _this = this;
if(timer){//如果有定时器,退出
return
}
timer = setTimeout(function(){
fn.apply(_this,_args);//定时器结束执行函数
timer = null;//清除定时器,可以再次进入
},delay)
}
}
let testThrottleFn = throttle(test,3000);
function test(a){
console.log('打印 '+a)
}
window.onscroll = function(){
testThrottleFn('bbbb')
}
new Date方式
function throttle(fn,delay){
let previous = 0;
return function(){
let _this = this;
let _argus = arguments;
let now = new Date();
//不同时间取值的new Date()是可以相减的
if(now-previous>delay){
fn.apply(_this,_argus);
previous = now;
}
}
}
let testThrottleFn = throttle(test,2000);
function test(b){
console.log('出现 '+b)
}
window.onscroll = function(){
testThrottleFn('8888')
}