Reputation: 353
I am looking for a timer to put on my website, and the timer would be set for an hour, and after it counts down to zero it resets back to one hour again. It also needs to be universal, so it displays the same for all users and does not reset back to 1hr if you refresh the page. I'm guessing this is relatively simple, however all I could find was timers which count to a certain time and stop, or timers which start back at zero after page refresh which is insufficient.
If someone could help, or knows of a link where something like that is available I would greately appreciate it!
Thanks in advance.
Upvotes: 0
Views: 2295
Reputation: 31
Here is a condition I know it will help.
ctsecs--;
if(ctsecs < 0) {
if(ctmnts > 0) {
ctsecs = 59;
ctmnts--;
if(cthrs > 0) {
ctmnts = 59;
cthrs--;
} else {
ctsecs = 0;
ctmnts = 0;
cthrs = 0;
}
}
}
Upvotes: 3
Reputation: 147403
If you want a timer that ticks every second, setInterval is a poor choice. It only runs at approximately the requested interval and will slowly drift. A clock using it will not be smooth unless you call it often, which is wasteful.
A better strategy is to use setTimeout to call itself sequentially, setting the lag based on the time to the next tick plus a small amount. e.g. a very simple clock:
<script>
function addZ(n) {
return (n<10? '0' : '') + n;
}
function update() {
var d = new Date();
// Set lag to 20ms after next full second
var lag = 1020 - d.getMilliseconds();
document.getElementById('d0').innerHTML = addZ(d.getHours()) + ':' +
addZ(d.getMinutes()) + ':' + addZ(d.getSeconds());
setTimeout(update, lag);
}
window.onload = update;
</script>
<div id="d0"></div>
If you are happy with using the system clock for your counter, and you want everyone to see the same numbers (more or less), you can use Date's UTC methods: getUTCHours
, getUTCMinutes
and getUTCSeconds
.
Upvotes: 0
Reputation: 3028
you can use ajax for this purpose. make a database entry on server about 60 minutes and update the time to client with ajax requests, this will be more secure than client side scripting.
Upvotes: 0
Reputation: 142921
You could have the timer just display the complement of the current minutes and seconds of UTC:
setInterval(function() {
var d = new Date;
var s = (60 - d.getUTCMinutes()) + ":" + (60 - d.getUTCSeconds());
$("#time").text(s);
}, 250);
Here's a demo page where you can see it in action.
Upvotes: 2
Reputation: 2311
Why not just get the current time, and only display the minutes? Otherwise, it'd have to be done server side.
Upvotes: 1