首页 > 其他 > 详细

函数节流throttle和防抖debounce

时间:2020-02-04 13:46:27      阅读:76      评论:0      收藏:0      [点我收藏+]

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);
}
}
}

函数节流throttle和防抖debounce

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!