import * as smartpromise from '@pushrocks/smartpromise'; /** * delay something, works like setTimeout * @param timeInMillisecond * @param passOn */ export let delayFor = async (timeInMillisecond: number, passOn?: T) => { await new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, timeInMillisecond); }); return passOn; }; /** * delay for a random time */ export let delayForRandom = async ( timeMinInMillisecond: number, timeMaxInMillisecond: number, passOn?: T ) => { await new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, Math.random() * (timeMaxInMillisecond - timeMinInMillisecond) + timeMinInMillisecond); }); return passOn; }; export class Timeout { promise: Promise; private _deferred: smartpromise.Deferred; private _timeout: any; private _cancelled: boolean = false; constructor(timeInMillisecondArg, passOn?: T) { this._deferred = smartpromise.defer(); this.promise = this._deferred.promise; this._timeout = setTimeout(() => { if (!this._cancelled) { this._deferred.resolve(passOn); } }, timeInMillisecondArg); } makeUnrefed() { this._timeout.unref(); } cancel() { this._cancelled = true; this.makeUnrefed(); } }