interface RequestIdleCallback { didTimeout : boolean ; timeRemaining : ( ) => number ; } declare global { interface Window { requestIdleCallback ( cb , options ? ) : NodeJS . Timer ; cancelIdleCallback ( id ) : void ; } } export class TimeScheduler { private timerId ? : any ; private idleId ? : any ; constructor ( private callback , private interval ) { } private intervalCallback = ( deadline ) => { if ( deadline . timeRemaining ( ) > 0 ) { this . callback ( ) ; } } ; private idleWork = ( ) => { if ( this . idleId ) { window . cancelIdleCallback ( this . idleId ) ; this . idleId = undefined ; } this . idleId = window . requestIdleCallback ( this . intervalCallback , { timeout : 1000 } ) ; } ; start ( ) { this . timerId = setInterval ( this . idleWork , this . interval ) ; } stop ( ) { if ( this . timerId ) { clearInterval ( this . timerId ) ; this . timerId = undefined ; } if ( this . idleId ) { window . cancelIdleCallback ( this . idleId ) ; this . idleId = undefined ; } } }