Debounce function does not work when directly not

2019-07-25 15:58发布

I am trying to use Ben Alman's debounce code. I have the following code but I don't see anything executing at all.

onChange() {
        var this_ = this
        if (this.autoRefreshOn) {
            Cowboy.debounce(function(e) {
                console.log("debounce worked");
                this_.doSomethingFunction();
            }, 250);
        }
    }

This onChange() function is fired from multiselect boxes like this:

<ss-multiselect-dropdown (ngModelChange)="onChange($event)"></ss-multiselect-dropdown>
<ss-multiselect-dropdown (ngModelChange)="onChange($event)"></ss-multiselect-dropdown>
<ss-multiselect-dropdown (ngModelChange)="onChange($event)"></ss-multiselect-dropdown>
<ss-multiselect-dropdown (ngModelChange)="onChange($event)"></ss-multiselect-dropdown>

When these select boxes are checked they continuously fire onChange() but I do not see any executions from the debounce function.

All of the examples I found on the web implement a debounce function that is bind to a button press or something like that.

1条回答
神经病院院长
2楼-- · 2019-07-25 16:18

You can add a debounce directly to your onChange() method and call the newly created debounced method directly in your template:

component.ts

  limitedOnChange = this.debounce(this.onChange, 250);

  onChange(event) { console.log('change detected: ', event) }

  debounce(fn, delay) {
    let timer = null;
    return function () {
      const context = this, args = arguments;
      clearTimeout(timer);
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);
    };
  }

component.html

  <ss-multiselect-dropdown (ngModelChange)="limitedOnChange($event)"></ss-multiselect-dropdown>
查看更多
登录 后发表回答