我有一个计时器,我想通过调用
开始 countdownTimer.start(600,'/page2.html');
显示计时器从600秒倒计时后,它将重定向到page2.html
我还想通过调用以下内容来恢复以前的计时器(来自cookie)。我只是使用cookie来保存它停止的值,所以如果刷新页面,它将重新开始计数而不是重新开始。
countdownTimer.resume(123, '/page2.html');
我遇到了各种各样的错误,关于内部html没有被定义(我假设这与函数顶部的变量没有被调用有关)。
有人可以帮我理解如何创建这样的javascript对象吗?它总是困惑我:/
var countdownTimer = (function() {
var elem = document.getElementById("countdown");
var url = '';
var end = 60;
var _second = 1000;
var _minute = 60000;
var _hour = 3600000;
var timer;
function pad (n, amount) {
return n > parseInt(Array(amount).join("9")) ? "" + n : "0" + n;
}
function showRemaining () {
var now = new Date().getTime();
var distance = end - now;
if (distance < 0 ) {
clearInterval( timer );
elem.innerHTML = "Offer Expired";
window.location.href = url;
return;
}
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var milliseconds = Math.floor( (distance % _second) );
elem.innerHTML = pad(minutes, 2) + ' <span>:</span> ';
elem.innerHTML += pad(seconds, 2) + ' <span>:</span> ';
elem.innerHTML += pad(milliseconds, 3);
}
var start = function (secondsToExpire, url) {
url = url;
end = new Date().getTime() + (secondsToExpire * 1000);
timer = setInterval(showRemaining, 1);
}
var resume = function (customEnd, url) {
url = url;
end = customEnd;
timer = setInterval(showRemaining, 1);
}
var currentTime = function () {
return 500;
}
return {
start: start,
resume: resume,
currentTime: currentTime
};
})();