export class StoppableTimeout { private stopped : boolean = false ; private timer : NodeJS . Timer ; private reject ? : ( err : Error ) => void ; wait ( delay ) { if ( this . stopped ) { return Promise . reject ( new Error ( 'timer stopped' ) ) ; } return new Promise ( ( resolve , reject ) => { this . timer = setTimeout ( resolve , delay ) ; this . reject = reject ; } ) ; } stop ( ) { clearTimeout ( this . timer ) ; this . stopped = true ; if ( this . reject ) { this . reject ( new Error ( 'timer stopped' ) ) ; } } }