首页 > 其他 > 详细

节流和防抖

时间:2018-12-20 10:54:17      阅读:129      评论:0      收藏:0      [点我收藏+]
let last = 0, timer = null; // 把上次触发事件和定时器存在全局

/**
* 防抖
* @param fn
* @param delay
* @returns {Function}
*/
debounce=(fn, delay)=>{
// let timer = null;
// 将debounce处理结果当作函数返回
return function () {
// 保留调用时的this上下文
let context = this
// 保留调用时传入的参数
let args = arguments

// 每次事件被触发时,都去清除之前的旧定时器
if(timer) {
clearTimeout(timer)
}
// 设立新定时器
timer = setTimeout(function () {
fn.apply(context, args)
}, delay)
}
}
/**
* 节流
* @param fn
* @param interval
* @returns {Function}
*/
throttle=(fn, interval)=>{
// 将throttle处理结果当作函数返回
return function () {
// 保留调用时的this上下文
let context = this
// 保留调用时传入的参数
let args = arguments
// 记录本次触发回调的时间
let now = +new Date()

// 判断上次触发的时间和本次触发的时间差是否小于时间间隔的阈值
if (now - last >= interval) {
// 如果时间间隔大于我们设定的时间间隔阈值,则执行回调
last = now;
fn.apply(context, args);
}
}
}
/**
* 节流防抖结合
* @param fn
* @param delay
* 用 Throttle 来优化 Debounce
*/
throttle=(fn, delay)=>{
// 将throttle处理结果当作函数返回
return function(){
// 保留调用时的this上下文
let context = this;
// 保留调用时传入的参数
let args = arguments;
// 记录本次触发回调的时间
let now = +new Date()

// 判断上次触发的时间和本次触发的时间差是否小于时间间隔的阈值
if(now - last < delay){
console.log("不触发")
clearTimeout(timer)
timer = setTimeout(function(){
last = now;
fn.apply(context, args);
}, delay)
}else{
console.log("触发")
// 如果时间间隔超出了我们设定的时间间隔阈值,那就不等了,无论如何要反馈给用户一次响应
last = now
fn.apply(context, args)
}
}
}

节流和防抖

原文:https://www.cnblogs.com/gwf93/p/10147918.html

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