2017-01-16 13:54:08 +00:00
|
|
|
import 'typings-global'
|
2017-06-04 22:32:01 +00:00
|
|
|
import * as smartq from 'smartq'
|
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) => {
|
|
|
|
setTimeout(
|
|
|
|
() => {
|
|
|
|
resolve()
|
|
|
|
},
|
|
|
|
timeInMillisecond
|
|
|
|
)
|
|
|
|
})
|
|
|
|
return passOn
|
|
|
|
}
|
|
|
|
|
|
|
|
export class Timeout<T> {
|
|
|
|
promise: Promise<T>
|
|
|
|
private _deferred: smartq.Deferred<T>
|
|
|
|
private _timeout: any
|
|
|
|
private _cancelled: boolean = false
|
|
|
|
constructor (timeInMillisecondArg, passOn?: T) {
|
|
|
|
this._deferred = smartq.defer<T>()
|
|
|
|
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()
|
|
|
|
}
|
2017-01-16 13:54:08 +00:00
|
|
|
}
|