export interface IThrottled { ( ) : void ; cancel ( ) : void ; } export interface IThrottleService { throttle ( f , wait ) : IThrottled ; } export class ThrottleService implements IThrottleService { $timeout : angular . ITimeoutService ; ngInject constructor ( $timeout ) { this . $timeout = $timeout ; } throttle ( f , wait ) { var timeout ; var previous = 0 ; var cancelled = false ; var vm = this ; var later = function ( ) { previous = ( new Date ( ) ) . getTime ( ) ; timeout = null ; f ( ) ; } ; var throttled = function ( ) { var now = ( new Date ( ) ) . getTime ( ) ; var remaining = wait - ( now - previous ) ; if ( cancelled ) { return ; } if ( remaining <= 0 || remaining > wait ) { if ( timeout ) { vm . $timeout . cancel ( timeout ) ; timeout = null ; } previous = now ; f ( ) ; } else if ( ! timeout ) { timeout = vm . $timeout ( later , remaining ) ; } } ; throttled . cancel = function ( ) : void { cancelled = true ; if ( timeout ) { vm . $timeout . cancel ( timeout ) ; } previous = 0 ; timeout = null ; } ; return < IThrottled > throttled ; } }