I'm trying to create a timer that counts down in years, months, days, hours, minutes, seconds and milliseconds. I've found a few guides online, but they are sort of not easy to understand, or do not do the milliseconds. Can anyone help me do something like this, say, for this friday at 13:30.
so it could read 0y 0m 2d 2h 11m 50ms
and counts down the milliseconds. I would show code to demonstrate that I have actually tried to do this myself, but it all failed so dismally that i'd be embarrassed to.
I also read this article, which makes me mistrust javascript timers a bit. Is this true, that they become so out of sync?
Thanks for any help!
Depends how you implement it.
If you read the time once and depend on the setInterval or/and setTimeout for the accuracy then yes .. they can get out of sync.
If you always get the current time for using in your calculations, then it can go out of sync like the rest of your system goes out of sync... meaning that it follows the clock of the computer.
Altering my answer at JavaScript / jQuery Countdown to add milliseconds you get
var end = new Date('13 Apr 2012 13:30:00');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24;
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
// handle expiry here..
clearInterval( timer ); // stop the timer from continuing ..
//alert('Expired'); // alert a message that the timer has expired..
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var milliseconds = distance % _second;
var countdownElement = document.getElementById('timer');
countdownElement.innerHTML = days + 'd ' +
hours + 'h ' +
minutes + 'm ' +
seconds + 's ' +
milliseconds + 'ms';
}
timer = setInterval(showRemaining, 10);
But it does not handle month and year as that needs more complex calculations to factor 28-31 day months and leap years..
Demo at http://jsfiddle.net/TaHtz/2/
Try this js fiddle: http://jsfiddle.net/QH6X8/185/
Set the end date with the end variable defined on the first line of the JavaScript.
If you don't want to update every 1 millisecond, then here is a jsfiddle updating every 60: http://jsfiddle.net/QH6X8/187/
Related
I would like to create a countdown timer for my resource. An example for this I took from Quasimodo's clone answer of this page.
From the code, I took some elements, since I only need minutes and seconds. And I don't need a 30 minute mark.
The code works great, but unlike the author of the question, I need the start to start and end at 1 minute of the next hour.
The changes that I made did not lead to the desired result:
secsRemaining = 3600 - (time.getUTCMinutes()+1)%60 * 60 - time.getUTCSeconds(),
and
mins = (Math.floor(secsRemaining / 60)+60),
This gave a result, but not the one that is needed. When the time on the clock becomes 00 minutes, then the code becomes 60 minutes and 00+ seconds. I need, for example, at 14:00:59 the timer has the values 00:01, and when 14:01:01 the timer has the values 59:59.
Please let me know how it can be changed to achieve the desired result. Perhaps you have a link to solutions. I couldn't find it on the Internet.
Code I am using:
var byId = document.getElementById.bind(document);
function updateTime() {
var time = new Date(),
secsRemaining = 3600 - (time.getUTCMinutes()) % 60 * 60 - time.getUTCSeconds(),
mins = (Math.floor(secsRemaining / 60)),
secs = secsRemaining % 60;
byId('min-part').textContent = mins;
byId('sec-part').textContent = secs;
setTimeout(updateTime, 1000 - (new Date()).getUTCMilliseconds()).toLocaleString();
}
updateTime();
<div>Time left before update: <span id="min-part"></span>:<span id="sec-part"></span></div>
Here is how I would do it
Generating a date at the next hour and 1 minutes
Calculating the number of millisecond between the current date and the next date
Display the time remaining
const minutes = document.getElementById('minutes')
const seconds = document.getElementById('seconds')
setInterval(() => {
const now = new Date()
const nextHours = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 1)
const nbMilisec = (nextHours - now)
const nbMinutes = parseInt((nbMilisec / 1000 / 60) % 60)
const nbSeconds = parseInt((nbMilisec / 1000) % 60)
minutes.innerHTML = String(nbMinutes).padStart(2, '0')
seconds.innerHTML = String(nbSeconds).padStart(2, '0')
}, 1000)
<div id="time">
Time left before update : <span id="minutes"></span> : <span id="seconds"></span>
</div>
If I understood well your needs, this should be the code you need:
var byId = document.getElementById.bind(document);
function updateTime()
{
var
time = new Date(),
// You need an hour of countdown, so 30 becomes 60
secsRemaining = 3600 - (time.getUTCMinutes()+60)%60 * 60 - time.getUTCSeconds(),
// integer division
// you want the timer to "end" at minute 1, so add 1 minute to the minutes counter
mins = (Math.floor(secsRemaining / 60) + 1) % 60,
secs = secsRemaining % 60
;
byId('min-total').textContent = secsRemaining;
byId('min-part').textContent = mins;
byId('sec-part').textContent = secs;
// let's be sophisticated and get a fresh time object
// to calculate the next seconds shift of the clock
setTimeout( updateTime, 1000 - (new Date()).getUTCMilliseconds() );
}
updateTime();
How do i make countdown timer that will be the same for everyone regardless their time on pc.
The script doesn't work as i wanted it to, basically anyone can change the timer with just changing date and time on their pc.
var end = new Date('07/31/2015 4:10 pm');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById('giveaway1').innerHTML = 'The Winner Has Been Chosen!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('giveaway1').innerHTML = days + 'days ';
document.getElementById('giveaway1').innerHTML += hours + 'hrs ';
document.getElementById('giveaway1').innerHTML += minutes + 'mins ';
document.getElementById('giveaway1').innerHTML += seconds + 'secs';
}
timer = setInterval(showRemaining, 1000);
Since local PC time is outside your control, you will have to get the reliable time from your server (or a third-party server) at least once.
Once you know what the (correct) server time is, you can subtract server time from local PC time to get the 'offset' (i.e. the difference between server time and local PC time).
Once you have that offset you can then at any time get the local PC time - via new Date() - and factor in the offset to get the 'correct' server time, without having to call the server each time.
I have the following timespan coming from a model in MVC:
timeTaken = "00:01:00";
Then I have a multiplier
multiply = "3";
Result: 00:03:00
What would be the best way to calculate this time?
I don't know a great deal of libraries. I was thinking of splitting the seconds, minutes and hours, dividing each one into seconds, multiplying then putting it back together.
However, I have this kind of calculations for many sections, it just seems a little mundane. Can I just multiply the time in a better manner?
Thanks
I am combining the snippets I found in multiple pages. Conversion of hh:mm:ss to seconds, multiply 3x and then again convert to hh:mm:ss.
var hms = '00:01:00'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var newSeconds= 3*seconds;
// multiply by 1000 because Date() requires miliseconds
var date = new Date(newSeconds * 1000);
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getSeconds();
// If you were building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time
// if (hh > 12) {hh = hh % 12;}
// These lines ensure you have two-digits
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
if (ss < 10) {ss = "0"+ss;}
// This formats your string to HH:MM:SS
var t = hh+":"+mm+":"+ss;
document.write(t);
JSFiddle
First you can convert them to seconds as below
var hms = "00:01:00";
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var newSeconds=seconds * 3;
var t = new Date();
t.setSeconds(newSeconds);
console.log(t);
DEMO
Update
To just obtain time do as below
var time=t.toTimeString().split(' ')[0]
DEMO
UPDATE
To obtain just hour from time you can do as follows
t.toTimeString().split(' ')[0].split(':')[0]
and to obtain hour in 12 hour format you can do as below:
var hour;
if(t.toTimeString().split(' ')[0].split(':')[0]>12)
hour=t.toTimeString().split(' ')[0].split(':')[0]-12;
else
hour=t.toTimeString().split(' ')[0].split(':')[0];
alert(hour);
UPDATED DEMO
I am making a game with php mysql and jquery which involves finding out 5 differences in two images within 30 seconds. Everything works fine but some users are able to submit scores(time taken to find all 5 differences) like 0.008 seconds which is next to impossible even if you play the same image multiple times and touch the screen with all 5 fingers.
Any idea how this could be possible? Just theory wise. Below is the count down timer code.
var end = new Date();
var temp = new Date();
end.setSeconds(temp.getSeconds()+30);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24;
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var milliseconds = Math.floor(distance % _second);
var countdownElement = document.getElementById('elapsed_time');
//countdownElement.innerHTML = seconds + ':' + milliseconds;
seconds=seconds+1;
//countdownElement.innerHTML = '00:' + seconds.toString();
var strmil = milliseconds.toString();
if(strmil.length==3){
strmil=strmil.substring(0, strmil.length - 1);
}
countdownElement.innerHTML = seconds + ':' + strmil;
if( seconds==0){
// handle expiry here..
clearInterval( timer ); // stop the timer from continuing ..
countdownElement.innerHTML = '00:00';
setTimeout(function(){
window.location='go to a page which shows the you timed out';
}, 1000);
}
}
if( $('#elapsed_time').length ){
timer = setInterval(showRemaining, 10);
}
Gathered from information the comments you gave me I think the problem is located where you perform your checks. The following probably happens in the application when this error occurs.
When the game starts it starts the timer.
The application then constantly checks if the differences have been found yet
An error occurs here and the application instantly receives that all the differences have been found.
The game stops the timer and shows the victory popup with around 0.001-0.008 seconds.
This entire process takes around 0.001-0.008 seconds which explains the score.
So you should probably check for the bug in the part where it checks the differences. The code you posted works fine and the bug is not found there.
Keep browser compatibility issues in mind, maybe the bug only occurs on certain browsers.
The following script counts down but it won't stop counting when it reaches the end time.
When it reaches zero, it start again from 60:00 to 0 (another hour).
When i skip the part
$time = str_replace(' ', 'T', $db[time]);
and do it like this:
var end = new Date('<?=$db[time]?>');
The counter is stopping correctly, but then the counter wont work at IE or Firefox only in Chrome.
Anyone know how to stop this counter:S Thanx!
$db[time] = Timestamp field in the database (2013-10-03 11:32:39)
The Script:
$time = str_replace(' ', 'T', $db[time]);
Java script
<script>
var end = new Date('<?=$time?>');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = 'ITS NOW TIME!</font><BR><BR>';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('countdown').innerHTML = '<font color="orange">' + minutes + ':';
document.getElementById('countdown').innerHTML += '<font color="orange">' + seconds + ' minutes</font>';
}
timer = setInterval(showRemaining, 1000);
</script>
I suggest you use
var countInterval = setInterval(function() { countdown(secondsRemaining); },1000) instead.
This way you won't have to play around with Date or Time objects. Just keep a count inside countdown() and clearInterval(countInterval) once you reach 60.
I'm a little suspicious of your innerHTML usage. Where is this script located in the HTML? I have a feeling it's getting re-evaluated after setting innerHTML. You could test the theory by putting a console.log("Started!") statement next to setInterval.
Also, look here:
document.getElementById('countdown').innerHTML = 'ITS NOW TIME!</font><BR><BR>';
You're "setting" (replacing) the innerHTML of an element so it will contain: text, and then a close-font tag. That might mess up your DOM. Finally, you shouldn't be setting innerHTML twice in two lines - set it once in a function, perhaps based on a variable.
(To clarify: Using innerHTML on its own isn't the worst thing - but with malformed HTML, or by adjusting an element too high in the heirarchy, it can have unintended effects)