Reputation: 85
I have added a javascript countdown timer to my page but i would like to add more than one timer inside my page. when i add more timers the seconds counter start to skip.
here's my markup code
<div class="fa countdown-timer" style="font-size: x-large">
<span class="fa hrRemaining"></span>:<span class="minRemaining"></span>:<span class="secRemaining"></span>
</div>
<div class="fa countdown-timer" style="font-size: x-large">
<span class="fa hrRemaining"></span>:<span class="minRemaining"></span>:<span class="secRemaining"></span>
</div>
<div class="fa countdown-timer" style="font-size: x-large">
<span class="fa hrRemaining"></span>:<span class="minRemaining"></span>:<span class="secRemaining"></span>
</div>
here's my javascrpit timer
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
var remSeconds = Math.floor(@timeRemaining);
var secondsCounter = Math.floor(remSeconds % 60);
var minutesCounter = Math.floor((remSeconds / 60) % 60);
var hoursCounter = Math.floor((remSeconds / 3600));
function formatNumber(number) {
if (number < 10)
return '0' + number;
else
return '' + number;
}
function startTimers() {
var $timers = $('.countdown-timer');
// See https://api.jquery.com/each/
$timers.each(function() {
// `this` is the current `.countdown-timer` being iterated by jQuery.each()
var $timer = $(this);
var $seconds = $timer.find('.secRemaining');
var $minutes = $timer.find('.minRemaining');
var $hours = $timer.find('.hrRemaining');
$seconds.text(formatNumber(secondsCounter));
$minutes.text(formatNumber(minutesCounter));
$hours.text(formatNumber(hoursCounter));
var _tick = setInterval(function() {
if ((remSeconds) > 0) {
if (hoursCounter > 0) {
if (minutesCounter == 0) {
minutesCounter = 60;
hoursCounter = hoursCounter - 1;
}
}
if (secondsCounter == 0) {
secondsCounter = 60;
minutesCounter = minutesCounter - 1;
}
secondsCounter = secondsCounter - 1;
remSeconds = remSeconds - 1;
$seconds.text(formatNumber(secondsCounter));
$minutes.text(formatNumber(minutesCounter));
$hours.text(formatNumber(hoursCounter));
} else {
clearInterval(_tick);
document.getElementById("tRemaining").innerHTML = "EXPIRED";
}
},
1000);
})
}
startTimers();
</script>
the seconds it skips is directly related to the number of timers i add to the page.
Upvotes: 0
Views: 360
Reputation: 14679
You're sharing these variables
var remSeconds = Math.floor(@timeRemaining);
var secondsCounter = Math.floor(remSeconds % 60);
var minutesCounter = Math.floor((remSeconds / 60) % 60);
var hoursCounter = Math.floor((remSeconds / 3600));
across all the timers. Move the declarations inside this
$timers.each(function() {
function's scope.
Upvotes: 1