防抖和节流函数
//防抖函数
function debounce (fn, delay) {
let timer = null;
return function () {
//接收this,该this当前指向dom元素
const that = this;
//接收参数
const args = arguments;
//清除上次定时
clearTimeout(timer);
//开启定时
timer = setTimeout(() => {
//改变this指向,并把event传回去
fn.apply(that, args);
}, delay);
}
}
//节流函数
function throttle (fn, delay) {
//定义上次执行时间
let lastTime = 0;
return function () {
//当前时间
let nowTime = Date.now();
//小于指定时间就直接return
if ((nowTime - lastTime) < delay)return;
fn.apply(this, arguments);
lastTime = nowTime;
}
}