函数节流throttle和防抖debounce

throttle 函数节流

不论触发函数多少次,函数只在设定条件到达时调用第一次函数设定,函数节流

1
2
3
4
5
6
7
8
9
10
11
let throttle  = function(fn,intervalTime){
let lastTime = 0;
return function(){
let ctx = this;
let now = new Date().getTime();
if(now-lastTime>= intervalTime){
lastTime = now;
fn.apply(this,arguments)
}
}
}

debounce 函数防抖

不论出发函数多少次,函数只在最后一次调用函数时开始计时,函数防抖

1
2
3
4
5
6
7
let debounce = function(fn,intervalTime){
let timer = null;
大专栏  函数节流throttle和防抖debounceine"> return function(){
if(timer)clearTimeout(timer)
timer = setTimeout(()=>fn.apply(this,arguments),intervalTime)
}
}

throttle debounce 结合优化

优化后的开源库版本的throttle函数

1
2
3
4
5
6
7
8
9
10
11
12
13
let throttle  = function(fn,intervalTime){
let last = 0;
let timer = null;
return function(){
let now = new Date.getTime();
if((now-last) < intervalTime}{
if(timer)clearTimeout(timer);
setTimeout(fn.apply(this,arguments),intervalTime);
}else{
fn.apply(this,arguments);
}
}
}

原文地址:https://www.cnblogs.com/lijianming180/p/12258737.html