Dennis Ich
Dennis Ich

Reputation: 3785

Polymer: Delay value changed execution

Got a simple Polymer template containing:

<paper-input floatingLabel label="Suche" value="{{search}}" error-message="Invalid input!"></paper-input>

and JS:

properties : {
    search : {
        type : String,
        notify : true,
        observer : 'searchChanged'
    }
},
searchChanged : function() {
    this.$.searchAjax.url = /search/" + this.search;
    this.$.searchAjax.generateRequest();
}

So everytime the value changes the server is queried with a new URL. This works good but I want to delay the request to the server for about 500ms to not search after every input the user makes but after he stopped typing for 500ms.

Upvotes: 2

Views: 1944

Answers (1)

Srik
Srik

Reputation: 2381

You can use debounce provided by polymer to group multiple event listeners.

debounce(jobName, callback, [wait]). Call debounce to collapse multiple requests for a named task into one invocation, which is made after the wait time has elapsed with no new request. If no wait time is given, the callback is called at microtask timing (guaranteed to be before paint).

You can read more about it https://www.polymer-project.org/1.0/docs/devguide/utility-functions.html

In your case, below modification should work:

properties : {
    search : {
        type : String,
        notify : true,
        observer : 'searchChanged'
    }
},
_getData: function() {
  this.$.searchAjax.url = '/search/' + this.search;
  this.$.searchAjax.generateRequest();
},
searchChanged : function() {
  this.debounce('getDataDebouce', this._getData, 500);
}

Upvotes: 4

Related Questions