我正在尝试创建一个计时器小部件,该小部件可以用几秒钟进行初始化,然后随时通过使用新的“秒数”进行新调用来进行倒计时来重置。到目前为止,我有这个可以很好地创建计时器并倒计时。
我要做的是首先在 _create 方法中调用 _destroy 方法来删除已经在元素上的计时器,并使用 window.clearInterval 来停止重新添加计时器。this.interval 在 _start 方法中设置,然后在 _destroy 方法中引用,但我认为问题在于 this.interval 的范围。
这是我到目前为止所拥有的,但我的 _destroy 方法似乎没有清除间隔,我不知道为什么。
$.widget('time.countdown', {
options : {
remaining : (2 * 24 * 60 * 60 * 1000),
updatefreq: 1000
},
_create : function () {
'use strict';
this._destroy();
},
_start: function () {
'use strict';
var secs = this.options.remaining;
this.interval = window.setInterval((function (elem, secs) {
return function () {
secs -= 1;
var days = Math.floor(secs / (24 * 60 * 60)),
div_hr = secs % (24 * 60 * 60),
hours = Math.floor(div_hr / (60 * 60)),
div_min = secs % (60 * 60),
minutes = Math.floor(div_min / 60),
div_secs = div_min % 60,
seconds = Math.ceil(div_secs),
time_parts = {
"d": days,
"h": hours,
"m": minutes,
"s": seconds
},
tstring = '',
c;
for (c in time_parts) {
if (time_parts.hasOwnProperty(c)) {
tstring += time_parts[c] + c + ' ';
}
}
elem.html(tstring);
};
}(this.element, secs)), this.options.updatefreq);
},
_destroy: function() {
'use strict';
if (this.interval !== undefined) {
window.clearInterval(this.interval);
}
this.element.html('');
}
});
任何人都可以对此有所了解吗?