smartdelay/ts/index.ts

79 lines
1.8 KiB
TypeScript
Raw Normal View History

2018-07-06 12:20:56 +00:00
import * as smartpromise from '@pushrocks/smartpromise';
2017-01-16 13:54:08 +00:00
2017-06-04 22:32:01 +00:00
/**
* delay something, works like setTimeout
2021-06-04 11:54:21 +00:00
* @param timeInMillisecondArg
* @param passOnArg
2017-06-04 22:32:01 +00:00
*/
2021-06-04 12:11:27 +00:00
export let delayFor = async <T>(
timeInMillisecondArg: number,
passOnArg?: T,
unrefedArg = false
) => {
2021-06-04 11:54:21 +00:00
const timeout = new Timeout(timeInMillisecondArg, null, unrefedArg);
await timeout.promise;
return passOnArg;
2018-07-06 12:20:56 +00:00
};
2017-06-04 22:32:01 +00:00
2017-10-09 09:33:59 +00:00
/**
* delay for a random time
*/
2018-07-06 12:20:56 +00:00
export let delayForRandom = async <T>(
2021-06-04 11:54:21 +00:00
timeMinInMillisecondArg: number,
timeMaxInMillisecondArg: number,
passOnArg?: T,
unrefedArg = false
2018-07-06 12:20:56 +00:00
) => {
2021-06-04 12:11:27 +00:00
await delayFor(
Math.random() * (timeMaxInMillisecondArg - timeMinInMillisecondArg) + timeMinInMillisecondArg,
null,
unrefedArg
);
2021-06-04 11:54:21 +00:00
return passOnArg;
2018-07-06 12:20:56 +00:00
};
2017-10-09 09:33:59 +00:00
2017-06-04 22:32:01 +00:00
export class Timeout<T> {
2018-07-06 12:20:56 +00:00
promise: Promise<T>;
private _deferred: smartpromise.Deferred<T>;
2020-07-11 21:33:34 +00:00
private _timeout;
2018-07-06 12:20:56 +00:00
private _cancelled: boolean = false;
2020-05-27 16:06:07 +00:00
2020-05-27 16:54:32 +00:00
private timeoutInMillis: number;
private started: number;
2021-06-04 11:54:21 +00:00
constructor(timeInMillisecondArg, passOn?: T, unrefedArg = false) {
2020-05-27 16:54:32 +00:00
this.timeoutInMillis = timeInMillisecondArg;
2018-07-06 12:20:56 +00:00
this._deferred = smartpromise.defer<T>();
this.promise = this._deferred.promise;
2017-06-04 22:32:01 +00:00
this._timeout = setTimeout(() => {
if (!this._cancelled) {
2018-07-06 12:20:56 +00:00
this._deferred.resolve(passOn);
2017-06-04 22:32:01 +00:00
}
2018-07-06 12:20:56 +00:00
}, timeInMillisecondArg);
2020-05-27 16:54:32 +00:00
this.started = Date.now();
2021-06-04 11:54:21 +00:00
if (unrefedArg) {
this.makeUnrefed();
}
2017-06-04 22:32:01 +00:00
}
2020-05-27 16:06:07 +00:00
/**
* unreffing a timeout causes the node process to not wait for completion before exit
*/
public makeUnrefed() {
2018-07-06 12:20:56 +00:00
this._timeout.unref();
2017-06-04 22:32:01 +00:00
}
2020-05-27 16:06:07 +00:00
/**
* cancels the timer
*/
public cancel() {
2018-07-06 12:20:56 +00:00
this._cancelled = true;
2020-07-11 21:33:34 +00:00
clearTimeout(this._timeout);
2017-06-04 22:32:01 +00:00
}
2021-06-04 12:11:27 +00:00
2020-05-27 16:54:32 +00:00
public getTimeLeft() {
const result = this.started + this.timeoutInMillis - Date.now();
return result > 0 ? result : 0;
}
2017-01-16 13:54:08 +00:00
}