blob: 89f62eecd85ef7c23f992423b992720456bae459 [file] [log] [blame]
Matteo Scandoloba0d92e2017-03-02 16:47:46 -08001export interface IXosDebouncer {
Matteo Scandolo968e7f22017-03-03 11:49:18 -08002 debounce(func: any, wait: number, context: any, immediate?: boolean): any;
Matteo Scandoloba0d92e2017-03-02 16:47:46 -08003}
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
Matteo Scandolo75171782017-03-08 14:17:01 -080015 // if 'immediate' call it immediately then wait for 'wait'
Matteo Scandoloba0d92e2017-03-02 16:47:46 -080016 // NOTE that we cannot use $timeout service to debounce functions as it trigger infiniteDigest Exception
Matteo Scandolo968e7f22017-03-03 11:49:18 -080017 public debounce(func: any, wait: number, context: any, immediate?: boolean) {
Matteo Scandoloba0d92e2017-03-02 16:47:46 -080018 let timeout;
Matteo Scandoloba0d92e2017-03-02 16:47:46 -080019 return function() {
Matteo Scandoloba0d92e2017-03-02 16:47:46 -080020 const args = arguments;
21 const later = function() {
22 timeout = null;
23 if (!immediate) {
24 func.apply(context, args);
25 }
26 };
27 const callNow = immediate && !timeout;
28 clearTimeout(timeout);
29 timeout = setTimeout(later, wait);
30 if (callNow) {
31 func.apply(context, args);
32 }
33 };
34 }
35}