You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
947 B

/* eslint-disable @typescript-eslint/no-this-alias,prefer-rest-params */
/**
*
* @param {function} func debounce
* @param {number} wait ,500ms
* @param {boolean} immediate
*/
export function debounce<F extends () => void>(func: F, wait = 500, immediate = false) {
let timeout: NodeJS.Timeout | undefined;
return function (...args: Parameters<F>) {
// @ts-ignore
const context = this;
// const args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
// 如果已经执行过,不再执行
const callNow = !timeout;
timeout = setTimeout(function () {
timeout = undefined;
}, wait);
if (callNow) func.apply(context, args);
// if (callNow) func(...args);
} else {
timeout = setTimeout(function () {
func.apply(context, args);
// func(...args);
}, wait);
}
};
}