凝ったオプションを使いたい場合は lodash を使いましょう
throttle.ts
function throttle(fn: (...args: any[]) => void, wait: number) {
let timerId: number | null = null;
return (...args: any[]) => {
if (timerId !== null) {
return;
}
timerId = window.setTimeout(() => {
timerId = null;
return fn(...args);
}, wait);
};
}
debounce.ts
function debounce(fn: (...args: any[]) => void, wait: number) {
let timerId: number | null = null;
return (...args: any[]) => {
if (timerId) {
clearTimeout(timerId);
}
timerId = window.setTimeout(() => {
fn(...args);
}, wait);
};
}