How to Run Function Once On Load (then by Observer

2019-08-14 14:52发布

问题:

I am trying to run getResponse once when this web component loads, and then each time the procedure property changes.

However, when trying to run this debounce function, it is invoked 4 times and getResponse runs after a delay, but 4 times instead of 1.

static get properties() {
    return {
      procedure: {
        type: String,
        observer: 'getResponse'
      },
      timeout: {
        type: Number,
        value: null
      }

    }
  }

  ready() {
    super.ready();
    this.debounce();
  }

  debounce() {
    console.log('debounce');
    this.procedure = 'getInventoryActive';
    clearTimeout(this.timeout) // Clear the timeout if it has already been set.
                               // This will prevent the previous task from executing if it has been less than <MILLISECONDS>
    let that = this;           // Make a new timeout set to go off in 800ms
    this.timeout = setTimeout( () => {
      that.getResponse();
    }, 8000);
  }

  getResponse() {
    // do something;
  }

}

How can I achieve this behavior?

P.S. Also tried this debounce method within the ready function, and it's still invoking getResponse 4 times... (https://codepen.io/tony19/pen/vxZVwx)

debounce() {
  this.procedure = 'name';
  this._debouncer = Polymer.Debouncer.debounce(this._debouncer, Polymer.Async.timeOut.after(8000), () => {
    this.getResponse();
  });
}