Thursday, June 11, 2015

Polymer Quicktip - debounce

One of the more hidden features of Polymer is the possibility to "debounce" multiple requests into one function invocation.

This is useful if you have a compute- or time-heavy function that depends on several (published) properties and needs to be executed when those properties get a new value, e.g. if you need to create a new ajax call depending on several parameters.

Here a simple sample to demonstrate this behaviour.
First the element without debounce:
Including this element as <without-debounce property1="foo" property2="bar"></without-debounce> will trigger the function twice when the element is first loaded, and even if you change both properties at the same time you still get two function calls.

Here the same element with the debounce functionality added:
Using this element the console.log will only be called once when the element loads and also only once when properties get changed during a definable time (300ms in this case). This causes a small, but mostly ignorable delay before the actual execution of the function.

An element that uses this functionality is the iron-ajax element to prevent executing the actual request until all properties have "finalised".

I'm using the same behavior for the same reason in my discovery-api-elements.

No comments:

Post a Comment