blob: 3d4011fee7c31aecc4ef6c334e4515a4b1f37714 [file] [log] [blame]
Matteo Scandoloba0d92e2017-03-02 16:47:46 -08001export interface IXosDebouncer {
2 debounce(func: any, wait: number, immediate?: boolean): any;
3}
4
5export class XosDebouncer implements IXosDebouncer {
6 static $inject = ['$log'];
7
8 constructor (
9 private $log: ng.ILogService
10 ) {
11
12 }
13
14 // wait for 'wait' ms without actions to call the function
15 // if 'immediate' call it immediatly then wait for 'wait'
16 // NOTE that we cannot use $timeout service to debounce functions as it trigger infiniteDigest Exception
17 public debounce(func: any, wait: number, immediate?: boolean) {
18 let timeout;
19 const self = this;
20 return function() {
21 const context = self;
22 const args = arguments;
23 const later = function() {
24 timeout = null;
25 if (!immediate) {
26 func.apply(context, args);
27 }
28 };
29 const callNow = immediate && !timeout;
30 clearTimeout(timeout);
31 timeout = setTimeout(later, wait);
32 if (callNow) {
33 func.apply(context, args);
34 }
35 };
36 }
37}