防抖
在指定的时间内只触发一次,如果在指定的时候再次触发,将重新计时
const clearTimer = (timer) => {
if (timer !== null) clearTimeout(timer);
return null;
};
// 非立即执行
function debounce(fn, time) {
let timer = null;
return function() {
let content = this;
let args = arguments;
timer = clearTimer(timer);
timer = setTimeout(() => {
timer = clearTimer(timer);
fn.apply(content, args);
}, time);
}
}
const clearTimer = (timer) => {
if (timer !== null) clearTimeout(timer);
return null;
};
// 立即执行
function debounce1(fn, time, immediate) {
let timer = null;
return function() {
let callNow = !timer && immediate;
let content = this;
let args = arguments;
timer = clearTimer(timer);
timer = setTimeout(() => {
timer = clearTimer(timer);
if (!immediate) fn.apply(content, args);
}, time);
if (callNow) fn.apply(content, args);
}
}
节流
降频,稀释执行的频率。降低执行的频率。
浏览器滚动条事件,默认触发频率是 5 ~7 ms 触发一次。
// 时间戳版本
function throttle(func, wait) {
let preTime = 0;
return function() {
let now = Date.now();
let content = this;
let args = arguments;
if (now - preTime > wait) {
func.apply(content, args);
preTime = now;
}
}
}
// 定时器版本
function throttle(func, wait) {
let timer = null;
return function() {
let content = this;
let args = arguments;
if (!timer) {
timer = setTimeout(() => {
timer = null;
clearTimeout(timer);
func.apply(content, args);
}, wait);
}
}
}