Reputation: 874
var timer = 60;
var interval = setInterval(function() {
timer--;
var H = Math.floor((timer % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var HH = (H < 9 ? "0" : "") + H;
var M = Math.floor((timer % (1000 * 60 * 60)) / (1000 * 60));
var MM = (M < 9 ? "0" : "") + M;
var S = Math.floor((timer % (1000 * 60)) / 1000);
var SS = (S < 9 ? "0" : "") + S;
$('.timer').text(HH + ":" + MM + ":" + SS);
if (timer === 0) clearInterval(interval);
}, 1000);
Well I'm not sure what to ask here, I'm pretty sure this should work following tutorials online for a live jQuery based timer. I've set the timer
, obtain the hours, minutes and seconds, adding a 0
if the value < 9
, yet the script isn't working...
Upvotes: 0
Views: 256
Reputation: 1028
The problem lies in the value of timer
. The calculations are all done in milliseconds, but I think you're using seconds for the timer
.
I've made a fix for that in the snippet below. I've also added three variables at the top so it's easier to define the starting value of the timer. You can simply set the initial number of hours, minutes and seconds and from there it will all be calculated to milliseconds.
In the example I've set the initial value to 03:00:08, so you don't have to wait a long time to see it jump to a new minute and hour.
var timerH = 3;
var timerM = 0;
var timerS = 8;
var timer = (timerH * 60 * 60 * 1000) + (timerM * 60 * 1000) + (timerS * 1000);
var interval = setInterval(function() {
timer -= 1000;
var H = Math.floor((timer % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var HH = (H < 9 ? "0" : "") + H;
var M = Math.floor((timer % (1000 * 60 * 60)) / (1000 * 60));
var MM = (M < 9 ? "0" : "") + M;
var S = Math.floor((timer % (1000 * 60)) / 1000);
var SS = (S < 9 ? "0" : "") + S;
$('.timer').text(HH + ":" + MM + ":" + SS);
if (timer === 0) clearInterval(interval);
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="timer">00:00:00</div>
Upvotes: 1