js防抖和节流
防抖 一定时间间隔后再触发
节流 一定时间内只能触发一次
防抖
var debounce = function debounce(fn, delay) {
let timer = null;
return function () {
let args = arguments; let context = this;
if (timer) {
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
} else {
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
}
}
}
节流
var throttle = function throttle(fn, delay) {
let timer = null,
remaining = 0,
previous = new Date();
return function () {
let now = new Date(),
remaining = now - previous,
args = arguments,
context = this;
if (remaining >= delay) {
if (timer) {
clearTimeout(timer);
}
fn.apply(context, args);
previous = now;
} else {
if (!timer) {
timer = setTimeout(function () {
fn.apply(context, args);
previous = new Date();
}, delay - remaining);
}
}
};
}

浙公网安备 33010602011771号