smartdelay/ts/index.ts

57 lines
1.3 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;
constructor(timeInMillisecondArg, passOn?: T) {
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);
2017-06-04 22:32:01 +00:00
}
2018-07-06 12:20:56 +00:00
makeUnrefed() {
this._timeout.unref();
2017-06-04 22:32:01 +00:00
}
2018-07-06 12:20:56 +00:00
cancel() {
this._cancelled = true;
this.makeUnrefed();
2017-06-04 22:32:01 +00:00
}
2017-01-16 13:54:08 +00:00
}