smartdelay/ts/index.ts

74 lines
1.7 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
* @param timeInMillisecond
* @param passOn
*/
2017-01-16 13:54:08 +00:00
export let delayFor = async <T>(timeInMillisecond: number, passOn?: T) => {
2017-06-04 22:32:01 +00:00
await new Promise((resolve, reject) => {
2018-07-06 12:20:56 +00:00
setTimeout(() => {
resolve();
}, timeInMillisecond);
});
return passOn;
};
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>(
timeMinInMillisecond: number,
timeMaxInMillisecond: number,
passOn?: T
) => {
2017-10-09 09:33:59 +00:00
await new Promise((resolve, reject) => {
2018-07-06 12:20:56 +00:00
setTimeout(() => {
resolve();
}, Math.random() * (timeMaxInMillisecond - timeMinInMillisecond) + timeMinInMillisecond);
});
return passOn;
};
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>;
private _timeout: any;
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;
2018-07-06 12:20:56 +00:00
constructor(timeInMillisecondArg, passOn?: T) {
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();
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;
this.makeUnrefed();
2017-06-04 22:32:01 +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
}