直接上代码
一、js
防抖
export function debounce(fn, time, immediate) {
let timer = null;
const debounced = function () {
const context = this;
const args = arguments;
if (timer) clearTimeout(timer);
if (immediate) {
const callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, time || 500);
if (callNow) fn.apply(context, args);
} else {
timer = setTimeout(function () {
fn.apply(context, args);
}, time || 500);
}
};
debounced.cancel = function () {
clearTimeout(timer);
timer = null;
};
return debounced;
}
节流
function throttle(func, wait, immediate = true) {
let prevTime = 0;
let first = true;
const execu = ({ currentTime, context, args }) => {
if (currentTime >= prevTime) {
func.apply(context, args);
first = true;
}
};
const reset = (currentTime) => {
if (first) {
prevTime = currentTime + wait;
first = false;
}
}
return function () {
const context = this;
const args = arguments;
const currentTime = Date.now();
if (immediate) {
execu({ currentTime, context, args });
reset(currentTime);
} else {
reset(currentTime);
execu({ currentTime, context, args });
}
}
}
二、Ts
防抖
type DebounceFunction<T extends any[]> = (...args: T) => void;
function debounce<T extends any[]>(
func: (...args: T) => void,
wait: number,
immediate: boolean = false
): DebounceFunction<T> {
let timeout: number | undefined;
return function (this: unknown, ...args: T) {
const context = this;
const later = () => {
timeout = undefined;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && timeout === undefined;
clearTimeout(timeout);
timeout = window.setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
节流
type ThrottleFunction<T extends any[]> = (...args: T) => void;
function throttle<T extends any[]>(
func: (...args: T) => void,
wait: number,
immediate: boolean = true
): ThrottleFunction<T> {
let lastTime: number = 0;
let timeout: number | undefined;
return function (this: unknown, ...args: T) {
const context = this;
const now = Date.now();
const later = () => {
lastTime = immediate ? Date.now() : 0;
timeout = undefined;
if (!immediate) func.apply(context, args);
};
if (immediate && timeout === undefined) {
func.apply(context, args);
lastTime = Date.now();
}
if (timeout !== undefined) return;
const remaining = wait - (now - lastTime);
if (remaining <= 0 || remaining > wait) {
if (!immediate) func.apply(context, args);
lastTime = now;
} else {
timeout = window.setTimeout(later, remaining);
}
};
}
如何使用
const fun1 = debounce(()=>{ 函数内容 },500,true) // 防抖
三个参数分别代表
1. 要防抖/节流的函数
2. 间隔时间
3. 是否立即执行