0

If I call a Polymer debouncer from a button click it works perfectly. I click 5 times in less than 2 seconds, prints only one timestamp:

myProofOfConcept(){ this.__debouncer = Polymer.Debouncer.debounce( .__debouncer, Polymer.Async.timeOut.after(2000), () => { console.log("HEY " + Date.now()); }); }

But if I call the exact same method from a Polymer properties change observer, it will wait the required 2 second timeout, and then console print as many times as the observer calls it, even if only 1 millisecond apart.

Is there some external factor that I don’t know about, that is driving this difference in behavior?

2 Answers2

0

EDIT: Control for debouncing across all instances of the element and for property changed from multiple places (button clicks and setInterval).

Usage seems to be fine when applied like:

<dom-module id="my-element">

<template>
  <style>
    :host {
      display: block;
    }
  </style>
  [[prop]]
  <button on-click="add">Test</button>
</template>

<script>
(function() {
  let DEBOUNCED_METHOD;
  HTMLImports.whenReady(function() {
    class MyElement extends Polymer.Element {
      static get is() { return 'my-element'; }
      static get properties() {
        return {
          prop: {
            value: 0,
            type: Number,
            observer: 'myProofOfConcept'
          }
        }
      }
      constructor() {
        super();
        let test = setInterval(() => {
          this.add();
        }, 400);
        setTimeout(() => {
          clearInterval(test);
        }, 4500)
      }
      add() {
        this.prop += 1;
      }
      myProofOfConcept(){
        DEBOUNCED_METHOD = Polymer.Debouncer.debounce(
          DEBOUNCED_METHOD,
          Polymer.Async.timeOut.after(2000),
          this.log);
      }
      log() {
        console.log("HEY " + Date.now());
      }
    }
    customElements.define(MyElement.is, MyElement);
  });
}())
</script>

Hope that helps!

Westbrook
  • 608
  • 5
  • 9
  • Like I said in my original post, it works great when it's all initiated by a button click. But not when the initiating activity is from an imported property element. I have some complex functions that are initiated when other elements (specifically firebase elements) change a property. When these same functions fire my method with debounced internals, the debouncer fails. – petecarapetyan Apr 18 '18 at 01:46
0

Here's something to look for if this ever happens to you.

If you debounce a method within a web component... and then you instantiate multiple instances of that component within your web app... it may appear to you that the debouncer is not working, when in fact it may be working, rather it is just working in multiple instances of the same web component.

I had a stray previous instance of the web component inside an entirely different page. Hadn't been used, or even noticed. I had just forgotten to remove it when I migrated it to a different page.