export class TimeoutError extends Error { constructor ( message ? ) { super ( message ) ; this . name = 'TimeoutError' ; } } export function delay ( ms ) { let localDelay ; const promise = new Promise ( resolve => { localDelay = setTimeout ( resolve , ms ) ; } ) ; ( promise as any ) . timeout = localDelay ; return promise ; } export function timeout ( promise , ms ) { const promiseDelay = delay ( ms ) ; function cancelDelay ( ) { clearTimeout ( ( promiseDelay as any ) . timeout ) ; } return Promise . race ( [ ( promise as any ) . finally ( cancelDelay ) , promiseDelay . then ( ( ) => { throw new TimeoutError ( ) ; } ) , ] ) ; }