Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 1 | export interface IXosDebouncer { |
Matteo Scandolo | 968e7f2 | 2017-03-03 11:49:18 -0800 | [diff] [blame] | 2 | debounce(func: any, wait: number, context: any, immediate?: boolean): any; |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 3 | } |
| 4 | |
| 5 | export 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 Scandolo | 7517178 | 2017-03-08 14:17:01 -0800 | [diff] [blame] | 15 | // if 'immediate' call it immediately then wait for 'wait' |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 16 | // NOTE that we cannot use $timeout service to debounce functions as it trigger infiniteDigest Exception |
Matteo Scandolo | 968e7f2 | 2017-03-03 11:49:18 -0800 | [diff] [blame] | 17 | public debounce(func: any, wait: number, context: any, immediate?: boolean) { |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 18 | let timeout; |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 19 | return function() { |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 20 | 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 | } |