我正在为某天创建倒计时。但是,由于某种原因,我制作的那个似乎无法正常工作。我希望使用setInterval每秒调用一次它,但它仅显示加载页面时的时间。
这是代码
// Timer
targetDate = new Date(2014, 8, 22, 0, 0, 0);
function tick(ddate, id) {
var dateNow = new Date();
var amount = ddate.getTime() - dateNow.getTime();
delete dateNow;
if (amount <= 0) {
document.getElementById(id).innerHTML="Now!";
} else {
var days, hours, mins, secs, out;
days = 0; hours = 0; mins = 0; secs = 0; out = "";
amount = Math.floor(amount/1000);
days = Math.floor(amount / 86400);
amount %= 86400;
hours = Math.floor(amount / 3600);
amount %= 3600;
mins = Math.floor(amount / 60);
amount %= 60;
secs = Math.floor(amount);
out += "There are ";
out += (days <= 9?'0':'') + days + " " + ((days == 1)?"day":"days") + ", ";
out += (hours <= 9?'0':'') + hours + " " + ((hours == 1)?"hour":"hours") + ", ";
out += (mins <= 9?'0':'') + mins + " " + ((mins == 1)?"min":"mins") + ", ";
out += (secs <= 9?'0':'') + secs + " " + ((secs == 1)?"sec":"secs") + " ";
out += "until the end of this semester";
document.getElementById(id).innerHTML = out;
}
}
function getCount() {
setInterval(tick(targetDate, "timer"), 1000);
}
window.onload = function() {
getCount();
};
有人可以指出我搞砸的部分,谢谢
您需要将一个函数传递给setInterval()
—您要传递调用函数的结果。
setInterval(function() { tick(targetDate, "timer"); }, 1000);
您的代码调用了该函数,然后将返回值(undefined
)传递给setInterval()
。因此,您的代码按要求填充了DOM元素,但只完成了一次。该setInterval()
呼叫只是被忽略。如上所述,通过setInterval()
将函数调用包装在另一个函数中,将按预期工作。
请注意,计时器服务不是超级准确的,并且当浏览器选项卡未处于活动状态时,浏览器不会按计划运行间隔计时器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句