防抖和节流的js实现
防抖:不论连续执行几次,只从最后一次计时,结束后执行要处理的函数。
function debounce(fn, delay) {
let timer = null;
return function() {
let context = this;
let args = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
};
}
// 要处理的函数
function handle() {
console.log(Math.random());
}
var container = document.getElementById('container')
container.addEventListener('scroll', debounce(handle, 1000));
节流:连续高频多次执行变为隔段时间执行多次的处理方式。
// 方法一:定时器实现
const throttle = function(fn,delay) {
let timer = null;
return function() {
let context = this;
let args = arguments;
if(!timer) {
timer = setTimeout(() => {
fn.apply(context,args)
clearTimeout(timer)
timer = null;
},delay)
}
}
}
// 方法二:时间戳
const throttle2 = function(fn, delay) {
let preTime = Date.now()
return function() {
const context = this
let args = arguments
let doTime = Date.now()
if (doTime - preTime >= delay) {
fn.apply(context, args)
preTime = Date.now()
}
}
}
// 要处理的函数
function handle() {
console.log(Math.random());
}
var container = document.getElementById('container')
container.addEventListener('scroll', debounce(handle, 1000));