2022-06-06 14:17:51 +00:00
|
|
|
export function debounce(func: Function, wait?: number, immediate?: boolean) {
|
2022-02-25 18:59:39 +00:00
|
|
|
let timeout: ReturnType<typeof setTimeout> | null;
|
2022-01-12 12:54:04 +00:00
|
|
|
function _debounce(...args: any[]) {
|
|
|
|
// @ts-ignore
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
|
|
const context = this;
|
|
|
|
const later = function __debounce() {
|
|
|
|
timeout = null;
|
|
|
|
if (!immediate) {
|
|
|
|
func.apply(context, args);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
const callNow = immediate && !timeout;
|
|
|
|
clearTimeout(timeout!);
|
2022-06-06 13:23:49 +00:00
|
|
|
// @ts-ignore
|
2022-01-12 12:54:04 +00:00
|
|
|
timeout = setTimeout(later, wait);
|
|
|
|
if (callNow) {
|
|
|
|
func.apply(context, args);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_debounce.stop = () => clearTimeout(timeout!);
|
|
|
|
return _debounce;
|
|
|
|
}
|