Reputation: 883
I want create a countdown timer for som sections of my asp.net sites with javascript.
The timer starts from various minutes or seconds. After countdown comes to zero, I want stop the timer tick and do somethings like redirect to another page.
I've found this code from google and it's ok, but never stop after countdown comes to zero. please help me to fix this bug.
<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>
Upvotes: 0
Views: 17597
Reputation: 63
Gotrank's accepted answer is great - one small bug though:
var fiveMinutes = 5,
...should be...
var fiveMinutes = 300,
...for five minutes (it is currently 5 seconds). I would have commented, but I don't have enough reputation points yet.
Upvotes: 3
Reputation: 199
You have to clear what setInterval return. Something like this.
<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>
Upvotes: 9