我有一个计时器,我想通过调用来启动
countdownTimer.start(600,'/page2.html');
在显示计时器从 600 秒开始倒计时后,它将重定向到 page2.html
我还想通过调用以下命令来恢复以前的计时器(从 cookie 中)。我只是使用cookies来保存它停止的值,所以如果页面被刷新,它将恢复计数而不是重新开始。
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
};
})();