Matteo Scandolo | fb46ae6 | 2017-08-08 09:10:50 -0700 | [diff] [blame] | 1 | |
| 2 | /* |
| 3 | * Copyright 2017-present Open Networking Foundation |
| 4 | |
| 5 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | * you may not use this file except in compliance with the License. |
| 7 | * You may obtain a copy of the License at |
| 8 | |
| 9 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | |
| 11 | * Unless required by applicable law or agreed to in writing, software |
| 12 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | * See the License for the specific language governing permissions and |
| 15 | * limitations under the License. |
| 16 | */ |
| 17 | |
| 18 | |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 19 | export interface IXosDebouncer { |
Matteo Scandolo | 968e7f2 | 2017-03-03 11:49:18 -0800 | [diff] [blame] | 20 | debounce(func: any, wait: number, context: any, immediate?: boolean): any; |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 21 | } |
| 22 | |
| 23 | export class XosDebouncer implements IXosDebouncer { |
| 24 | static $inject = ['$log']; |
| 25 | |
| 26 | constructor ( |
| 27 | private $log: ng.ILogService |
| 28 | ) { |
| 29 | |
| 30 | } |
| 31 | |
| 32 | // wait for 'wait' ms without actions to call the function |
Matteo Scandolo | 7517178 | 2017-03-08 14:17:01 -0800 | [diff] [blame] | 33 | // if 'immediate' call it immediately then wait for 'wait' |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 34 | // 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] | 35 | public debounce(func: any, wait: number, context: any, immediate?: boolean) { |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 36 | let timeout; |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 37 | return function() { |
Matteo Scandolo | ba0d92e | 2017-03-02 16:47:46 -0800 | [diff] [blame] | 38 | const args = arguments; |
| 39 | const later = function() { |
| 40 | timeout = null; |
| 41 | if (!immediate) { |
| 42 | func.apply(context, args); |
| 43 | } |
| 44 | }; |
| 45 | const callNow = immediate && !timeout; |
| 46 | clearTimeout(timeout); |
| 47 | timeout = setTimeout(later, wait); |
| 48 | if (callNow) { |
| 49 | func.apply(context, args); |
| 50 | } |
| 51 | }; |
| 52 | } |
| 53 | } |