Question

I am attempting to build a polymer countdown widget.

In Javascript I would write a similar function to this and keep inserting the updated countdown time into the required ID element.

 setInterval(function () {
   //Work out time till event horizon
   //Shove the new time into the associated element
   countdown.innerHTML = days + "d, " + hours + "h, "+ minutes + "m, " + seconds + "s";
 }, 1000); 

In Polymer I am uncertain how to go about this as I am unsure how to go about using setInterval in Polymer... Here is some sudo code:

                <polymer-element name="countdown-element">
                <template>
                      <div id="countDown">{{counter}}</div> 
                </template>
                <script>
                    Polymer('countdown-element', {
                        counter: function() {
                              //Do stuff
                        }
                    });

                </script>
            </polymer-element>

How do I go about repeatedly sending the count down time to the counter ID location?

Was it helpful?

Solution

I think what you want is a combination of the two-way data binding that comes with Polymer and the async method described in the "advanced topics" here: http://www.polymer-project.org/docs/polymer/polymer.html#additional-utilities

Here is a JSBin with a simple countdown.

OTHER TIPS

Here's a simple countdown element in Polymer 3:

<html>
<body>
<script type="module">
  import { PolymerElement, html } from 'https://unpkg.com/@polymer/polymer/polymer-element.js?module'

  class CountdownElement extends PolymerElement {

    static get properties () { return {counter: Number} }

    ready () {
      super.ready()
      this.counter = 1000;
      this.updateCounter()
    }

    updateCounter () {
      this.counter -= 1;
      setTimeout(() => this.updateCounter(), 1000)
    }

    static get template () { return html`<div>Countdown: [[counter]]</div>` }
  }

  customElements.define('countdown-element', CountdownElement)
</script>

<countdown-element></countdown-element>
</body>
</html>

This example works without polyfills in Chrome and Firefox, you can try this in CodePen.

(This is also useful for building an ordinary clock by using clock instead of counter and setting it in updateClock() with e.g. this.clock = new Date().toLocaleTimeString() – but you need a countdown clock instead and seem to have existing logic for calculating the remaining time until the event already.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top