我想用javascript为我的asp.net网站的som部分创建一个倒数计时器。
计时器从几分钟或几秒开始。在倒计时到零之后,我想停止计时器滴答并做一些事情,比如重定向到另一页
我从谷歌找到了这个代码,没关系,但在倒计时到零之后永远不会停止。请帮我解决这个问题。
<head>
<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (timer-- < 0) {
//window.location = "http://www.example.com";
clearInterval(timer);
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
</script>
</head>
<body>
<div>Registration closes in <span id="time">05:00</span></div>
<form id="form1" runat="server">
</form>
</body>
答案 0 :(得分:4)
您必须清除setInterval返回的内容。这样的事情。
<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var end =setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
//window.location = "http://www.example.com";
clearInterval(end);
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
</script>
</head>
<body>
<div>Registration closes in <span id="time">05:00</span></div>
<form id="form1" runat="server">
</form>
&#13;
答案 1 :(得分:1)
var fiveMinutes = 5,
......应该......
var fiveMinutes = 300,
...五分钟(现在是5秒)。我会评论,但我还没有足够的声望点。