我正在尝试构建一个聚合物倒计时小部件。
在Javascript中,我会为此编写一个类似的函数,并继续将更新的倒计时时间插入所需的ID元素。
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);
在Polymer中,我不确定如何解决这个问题,因为我不确定如何在Polymer中使用setInterval ...这里有一些sudo代码:
<polymer-element name="countdown-element">
<template>
<div id="countDown">{{counter}}</div>
</template>
<script>
Polymer('countdown-element', {
counter: function() {
//Do stuff
}
});
</script>
</polymer-element>
如何重复向计数器ID位置发送倒计时时间?
我想你想要的是Polymer附带的双向数据绑定和“高级主题”中描述的async
方法的组合:http://www.polymer-project.org/docs/polymer/polymer.html#additional-utilities
Here is a JSBin简单的倒计时。
这是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>
此示例在Chrome和Firefox中没有polyfill的情况下工作,您可以在CodePen中尝试此操作。
(这对于通过使用clock
而不是counter
来构建普通时钟也很有用,并且使用updateClock()
将其设置在this.clock = new Date().toLocaleTimeString()
中 - 但是你需要一个倒计时时钟而且似乎有用于计算事件之前的剩余时间的逻辑。)