防抖与节流
防抖与节流
-
函数防抖是指在事件被触发 n 秒后再执行回调,如果在这 n 秒内事件又被触发,则重新计时。这可以使用在一些点击请求的事件上,避免因为用户的多次点击向后端发送多次请求。
-
函数节流是指规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。节流可以使用在 scroll 函数的事件监听上,通过事件节流来降低事件调用的频率。
防抖
// 立即执行版
function debounce(fn, wait){
var timer = null;
var valid = true;
return function(){
var context = this,
args = arguments;
if(timer) {
clearTimeout(timer);
timer = null;
}
if(valid){
valid = false;
fn.apply(context, args);
}
timer = setTimeout(()=>{
valid = true;
},wait);
}
}
// 非立即执行
function debounce(fn, wait){
var timer = null;
return function(){
var context = this,
args = arguments;
if(timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(()=>{
fn.apply(context, args);
},wait);
}
}
function test(){
console.log('xxxxxxxx');
}
window.onscroll = debounce(test, 1000);
节流
// 立即执行版
function throttle(fn, wait){
var pre = null;
return function(){
var context = this,
args = arguments;
var now = new Date().getTime();
if(pre ==null || now-pre>=wait){
fn.apply(context, args);
pre = now;
}
}
}
// 非立即执行版
function throttle(fn, wait){
var pre = new Date().getTime();
return function(){
var context = this,
args = arguments;
var now = new Date().getTime();
if(now-pre>=wait){
fn.apply(context, args);
pre = now;
}
}
}
function test(){
console.log('xxxxxxxx');
}
window.onscroll = throttle(test, 1000);

浙公网安备 33010602011771号