timers-obj
Version:
Timers as objects
109 lines (108 loc) • 2.24 kB
JavaScript
/// <reference types="node" />
export class Immediate {
constructor(callback, ...args) {
this.timer = setImmediate(callback, ...args);
}
close() {
if (this.timer) {
clearImmediate(this.timer);
this.timer = undefined;
}
return this;
}
hasRef() {
return this.timer?.hasRef() || false;
}
ref() {
this.timer?.ref();
return this;
}
unref() {
this.timer?.unref();
return this;
}
[Symbol.dispose]() {
this.close();
}
}
export class Interval {
/**
* @param delay - ms
*/
constructor(delay, callback, ...args) {
this.timer = setInterval(callback, delay, ...args);
}
close() {
if (this.timer) {
clearInterval(this.timer);
this.timer = undefined;
}
return this;
}
hasRef() {
return this.timer?.hasRef() || false;
}
ref() {
this.timer?.ref();
return this;
}
unref() {
this.timer?.unref();
return this;
}
refresh() {
this.timer?.refresh();
return this;
}
[Symbol.dispose]() {
this.close();
}
}
export class Timeout {
/**
* @param delay - ms
*/
constructor(delay, callback, ...args) {
this.timer = setTimeout(callback, delay, ...args);
}
close() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = undefined;
}
return this;
}
hasRef() {
return this.timer?.hasRef() || false;
}
ref() {
this.timer?.ref();
return this;
}
unref() {
this.timer?.unref();
return this;
}
refresh() {
this.timer?.refresh();
return this;
}
[Symbol.dispose]() {
this.close();
}
}
export function immediate(callback, ...args) {
return new Immediate(callback, ...args);
}
/**
* @param delay - ms
*/
export function interval(delay, callback, ...args) {
return new Interval(delay, callback, ...args);
}
/**
* @param delay - ms
*/
export function timeout(delay, callback, ...args) {
return new Timeout(delay, callback, ...args);
}