转自: https://blog.csdn.net/weixin_44429874/article/details/108984293
关于前端防抖、节流函数封装
总结:
个人理解.
1. 防抖:
// 防抖函数:当一个事件触发后的n秒内执行,当n秒内再次触发事件,重新开始计算计时器,当n秒内重新反复触发,回调永远不会执行.
function debounce(fn,time,triggleNow){
// 定义是否马上触发事件处理函数
var t = null,
res;
//定义一个空的定时器
var debounced = function () {
var _seelf = this;
args = arguments;
//进入后首先清除定时器
if (t) {
clearTimeout(t)
}
if (triggleNow) {
var exec = !t
t = setTimeout(function(){
t = null
},time)
if (exec) {
res = fn.apply(_seelf,args)
}
}else{
//
t = setTimeout(function(){
res = fn.apply(_seelf,args)
},time)
}
return res
}
debounced.remove = function () {
clearTimeout(t)
t = null
//清除定时器
}
return debounced;
}
2. 节流:
函数节流,当事件被触发的n秒内只执行一次事件处理函数.
function throttle(fn, delay) {
var t = null,
begin = new Date().getTime();
//定义开始时间
return function () {
var _self = this,
args = arguments,
curr = new Date().getTime();
clearTimeout(t);
if (curr - begin >= delay) {
//两次输入时间间隔小于定义的延迟时间则触发
fn.apply(_self, args);
begin = curr
} else {
t = setTimeout(function () {
fn.apply(_self, args)
}, delay)
}
}
}
转载: 看的B站大佬视频, up号:前端小野森森