/**
* 防抖:连续执行的函数,只有超过指定间隔时间才会真正执行
* 防抖函数工厂方法,返回具有防抖功能的函数
* @param fn 需要包装防抖功能的方法
* @param delay 重置时间
*/
function debounce(fn, delay) {
let timer = null // 创建定时器
return function() {
// 获取函数的作用域和变量
let that = this;
let args = arguments;
if(timer) { // 如果已经存在定时器,清除定时器
clearTimeout(timer)
}
timer = setTimeout(function(){ // 创建一个新的定时器,重新定时
fn.apply(that, args)
}, delay)
}
}
// 测试代码
window.addEventListener(
'scroll',
debounce(function(e){console.log(Math.random(), e)}, 1000)
);
/**
* 节流:每隔一段时间只执行一次函数
* 节流函数工厂方法,返回具有节流能力的函数
*/
function throttle(func, delay) {
let timer = null;
return function() {
// 获取函数的作用域和变量
let that = this;
let args = arguments;
// 如果已经存在定时器了,忽略需要执行的方法,如果没有定时器,则创建一个新定时器
if (!timer) {
timer = setTimeout(function() {
func.apply(that, args);
timer = null;
}, delay);
}
}
}
// 测试代码
window.addEventListener(
'scroll',
throttle(function(e){console.log(Math.random(), e)}, 1000)
);