blob: e8e479d2f532cd6f74697329978d12c15f9b4139 [file] [log] [blame]
Matteo Scandolofb46ae62017-08-08 09:10:50 -07001
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 Scandoloba0d92e2017-03-02 16:47:46 -080019export interface IXosDebouncer {
Matteo Scandolo968e7f22017-03-03 11:49:18 -080020 debounce(func: any, wait: number, context: any, immediate?: boolean): any;
Matteo Scandoloba0d92e2017-03-02 16:47:46 -080021}
22
23export 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 Scandolo75171782017-03-08 14:17:01 -080033 // if 'immediate' call it immediately then wait for 'wait'
Matteo Scandoloba0d92e2017-03-02 16:47:46 -080034 // NOTE that we cannot use $timeout service to debounce functions as it trigger infiniteDigest Exception
Matteo Scandolo968e7f22017-03-03 11:49:18 -080035 public debounce(func: any, wait: number, context: any, immediate?: boolean) {
Matteo Scandoloba0d92e2017-03-02 16:47:46 -080036 let timeout;
Matteo Scandoloba0d92e2017-03-02 16:47:46 -080037 return function() {
Matteo Scandoloba0d92e2017-03-02 16:47:46 -080038 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}