karlkoder-playground/js/debounce.js

27 lines
604 B
JavaScript

export class Debounce {
timer = null;
lastCall = 0;
constructor(timeout) {
this.timeout = timeout;
}
run(fn) {
const now = Date.now();
if (this.timer === null && now - this.lastCall > this.timeout) {
fn();
this.lastCall = now;
return;
}
if (this.timer !== null) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
fn();
this.lastCall = Date.now();
this.timer = null;
}, this.timeout);
}
}