redis-smq-common
Version:
RedisSMQ Common Library provides many components that are mainly used by RedisSMQ and RedisSMQ Monitor.
48 lines • 1.27 kB
JavaScript
import { EventEmitter } from '../event/index.js';
import { TimerError } from './errors/index.js';
export class Timer extends EventEmitter {
timer = null;
onTick = () => {
if (!this.timer)
this.emit('error', new TimerError('Expected a non-empty timer property'));
else {
const { fn, periodic } = this.timer;
if (!periodic)
this.timer = null;
fn();
}
};
setTimeout(fn, timeout) {
if (this.timer) {
return false;
}
this.timer = {
timer: setTimeout(() => this.onTick(), timeout),
periodic: false,
fn,
};
return true;
}
setInterval(fn, interval = 1000) {
if (this.timer) {
return false;
}
this.timer = {
timer: setInterval(() => this.onTick(), interval),
periodic: true,
fn,
};
return true;
}
reset() {
if (this.timer) {
const { timer, periodic } = this.timer;
if (periodic)
clearInterval(timer);
else
clearTimeout(timer);
this.timer = null;
}
}
}
//# sourceMappingURL=timer.js.map