export default class Scheduler { interval : number ; scheduledAt : number ; lastCalledAt : number ; timer ? : number ; callFn : ( ) => void ; constructor ( options ) { this . interval = options . interval || 5 ; this . scheduledAt = 0 ; this . lastCalledAt = 0 ; this . timer = undefined ; this . callFn = options . fn ; window . addEventListener ( "online" , ( ) => this . schedule ( ) ) ; window . addEventListener ( "offline" , ( ) => this . abort ( ) ) ; } schedule ( customIntervalSecs ? ) { if ( this . scheduledAt > 0 || ! navigator . onLine ) { return ; } this . scheduledAt = Date . now ( ) ; let interval = this . interval * 1000 ; if ( this . lastCalledAt < Date . now ( ) - interval ) { interval = 0 ; } if ( typeof customIntervalSecs === "number" ) { interval = customIntervalSecs * 1000 ; } this . timer = setTimeout ( ( ) => this . call ( ) , interval ) ; } abort ( ) { try { clearTimeout ( this . timer ) ; this . timer = undefined ; this . scheduledAt = 0 ; } catch ( err ) { } } reschedule ( customInterval ) { this . abort ( ) ; this . schedule ( customInterval ) ; } call ( ) { this . lastCalledAt = Date . now ( ) ; this . scheduledAt = 0 ; this . timer = undefined ; this . callFn ( ) ; } }