blob: 05341062565271c3925b745db49ae3229ee0565d [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
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
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}