Constant 12 hour countdown with moment.js - javascript

I'm trying to make a countdown using moment.js and jQuery. It's supposed to countdown to 12.00, and when it has passed 12.00, it should count down to 24.00 etc. So always count down the next 12 hours. It also has to be in UTC. This is what I have right now and it works fine, except when it has passed 12.00, it says "Timer done".
How can I achieve this in the best way?
var currentTime, endTime, timeDif;
currentTime = moment.now().format('X');
endTime = moment(moment.utc(12, "HH")).format('X');
function roundEndTimer() {
var Hours, Minutes, Seconds;
timeDif = endTime - currentTime;
function updateTime (){
Seconds = timeDif;
Hours = Math.floor(Seconds/3600);
Seconds -= Hours * 3600;
Minutes = Math.floor(Seconds/60);
Seconds -= Minutes * 60;
}
function tick (){
clearTimeout(timer);
updateTime();
displayTime();
if(timeDif > 0) {
timeDif - 1;
timer = setTimeout(tick, 1*1000)
}else {
$("#roundendtime").html("Timer done");
}
}
function displayTime() {
var out;
out = moment().hours(Hours).format('HH')+':'+moment().minutes(Minutes).format('mm')+':'+moment().seconds(Seconds).format('ss');
$("#roundendtime").html(out);
}
var timer = setTimeout(tick, 1*1000);
}

Related

How to make this countdown repeat after the time runs out?

I'm very new to Javascript and I found myself stuck with this issue. I want to make this countdown repeat after the time runs out, however I'm not really sure how to do it, and my attempts to make it work failed. Would appreciate help how to do it, Thanks.
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) {
// here's the problem. not sure how to make it repeat
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Tried using clearInterval() and setTimeout() but instead of it working the countdown either went past 00:00 (00:0-1 and so on) or just didn't work at all.
You can reset timer:
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) {
timer = duration;
}
}, 1000);
}
What you're describing is a forever countdown.
Note that eventhough you specify 1000 in the setInterval(). The timer isn't precise, so the callback may fire less than or greater than 1000ms. It is much safer to capture the startTime and then calculate the currentTime when the callback fires and measure the elapsedTime. This will give a true indication of elapsed time regardless of whether the timer is running slow or fast.
Because of the reset requirement. I actually infer that the timer is an infinite loop. We run it forever. There is no description as to when the timer is aborted, so, we just continue measuring currentTime and note elapse.
I use elapsedTime = (currentTime - startTime) / 1000 to calculate the elapsed time in seconds. Then, I elapsed % duration to make the counter stop at the duration and reset. Finally, I flip the math countdown = duration - 1 - (elapsedTime % duration) so instead of counting up, it counts down.
We then break down countdown into the minutes and seconds components.
Below is a fully working example that uses jQuery.
function startTimer(duration, display) {
let startTime = Date.now();
setInterval(function() {
let currentTime = Date.now();
let elapsedTime = Math.floor((currentTime - startTime) / 1000);
let countdown = duration - 1 - (elapsedTime % duration);
let minutes = Math.floor(countdown / 60).toString().padStart(2, "0");
let seconds = (countdown % 60).toString().padStart(2, "0");
display.text(minutes + ":" + seconds);
}, 1000 );
}
let fiveMinutes = 60 * 5;
let display = $("#time");
startTimer(fiveMinutes, display);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="time">mm:ss</label>

How to implement a refresh status in Javascript?

So I'm trying to do a refresh status in which if the page was refreshed under 5 minutes, it would say "Updated Just Now," and if it was updated over 5 minutes ago, it would say, "Updated Moments Ago." Below is my Javascript:
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
var seconds = Math.round(timeDiff);
if (seconds < 10) {
time = "Updated Just Now";
} else {
time = "Updated Moments Ago";
}
document.getElementById("demo").innerHTML = time;
}
window.onload = start
window.onload = end
However, it is very buggy and sometimes doesn't work at all. Any help will be appreciated.
Unless I missed something, I think You can use setTimeout. Initially set the HTML to 'Updated just now'.
const timeout = 5 * 60 * 1000
const changeText = () => {
document.getElementById("counter").innerHTML = "Updated moments ago";
}
setTimeout(changeText, timeout)
sandbox
You can simply do this instead of doing that stuff.
/* Note That 1000 is equivalent of 1 seconds */
setTimeout(function(){
document.getElementById("demo").innerHTML = "Updated Just Now";
}, 30000); /* This value is equivalent of 30 seconds */
setTimeout(function(){
document.getElementById("demo").innerHTML = "Updated Moments Ago";
}, 300000); /* This value is equivalent of 5 minutes */

Javascript Descending Timer with Minutes, Seconds and Milliseconds

I have searched all over internet a lot but could not find solution.
I want a timer with descending order with minutes, seconds and milliseconds. i.e. 05:59:999 -> 5 Minutes, 59 Seconds, 999 Milliseconds.
Below is my code which give me just minutes and seconds :
var countdownTimer = '';
var upgradeTime = 300; // total sec row from the table
var seconds = upgradeTime;
function timer()
{
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
document.getElementById('timer1').innerHTML = pad(minutes) + " : " + pad(remainingSeconds);
document.getElementById("timer1").style.border = "1px solid";
document.getElementById("timer1").style.padding = "4px";
}
function pad(n)
{
return (n < 10 ? "0" + n : n);
}
$('#acstart').on('click', function(e) // Start the timer
{
clearInterval(countdownTimer);
countdownTimer = setInterval('timer()', 1000);
});
I found fiddle with seconds and milliseconds here is the link :
http://jsfiddle.net/2cufprgL/1/
On completion of the timer I need to call other action.
Thanks
Using the fiddle you included, you only need to update the displayCount function to get the result you want.
function displayCount(count) {
let res = Math.floor(count / 1000);
let milliseconds = count.toString().substr(-3);
let seconds = res % 60;
let minutes = (res - seconds) / 60;
document.getElementById("timer").innerHTML =
minutes + ' min ' + seconds + ' s ' + milliseconds + ' ms';
}
Note that your fiddle has the correct approach to countdown, everytime the timer ticks it measures the actual time left it doesn't assume that the timer was 'on time'.
I wouldn't call this clean. But I did follow through using your code. I did change it to recursive setTimeout() though.
What I did is call the interval faster than 1000ms, set a specific speed variable and then properly decrement seconds while checking for a flag when seconds becomes 0, this flag then calls stopTimer().
var countdownTimer = '';
var upgradeTime = 3; // total sec row from the table
var seconds = upgradeTime;
var milliseconds = seconds * 1000;
var speed = 50; //interval speed
function timer()
{
milliseconds = (seconds * 1000) - speed; //decrement based on speed
seconds = milliseconds / 1000; //get new value for seconds
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = (seconds % 60).toFixed(3);
if(seconds <= 0){ stopTimer(); return; } //sets a flag here for final call
document.getElementById('timer1').innerHTML = pad(minutes) + " : " + pad(remainingSeconds);
document.getElementById("timer1").style.border = "1px solid";
document.getElementById("timer1").style.padding = "4px";
setTimeout('timer()', speed);
}
function stopTimer(){
clearTimeout(countdownTimer);
console.log("IT HAS BEEN DONE");
document.getElementById('timer1').innerHTML = "00 : 00.000"
}
function pad(n)
{
return (n < 10 ? "0" + n : n);
}
clearTimeout(countdownTimer)
countdownTimer = setTimeout('timer()', speed);
<div id="timer1"></div>
Something that sorta works logically right now. It's a tad unstable because of what I was trying to do. https://codesandbox.io/s/8xr1kx8r68
Momentjs with Countdown library - its a little outdated and unmaintained but looks like it does something like what you want.
https://github.com/icambron/moment-countdown
http://countdownjs.org/readme.html

Get elapsed time in Javascript between two timestamps

I have a method which takes a while to execute and I want to calculate how much take the execution of method:
var start = Date.now();
execute();
var final = Date.now();
var diff = final - start;
var seconds = diff / 1000;
var minutes = 0;
var hours = 0;
while(seconds >= 60)
{
minutes++;
seconds = Math.round(seconds/60);
}
while(minutes >= 60) {
hours++;
minutes = Math.round(minutes/60);
}
But I don't get correct information for minutes and seconds. Where is my mistake ?
The method takes somewhere 1 minute and few seconds, but in log shows only 20-40 seconds..
startTime = Date.now();
execute();
endTime = Date.now();
totalSeconds = (endTime -startTime)/1000
hours = Math.floor(totalSeconds/3600)
minutes = Math.floor((totalSeconds%3600)/60)
seconds = Math.floor((totalSeconds%3600)%60)
console.log(hours, minutes, seconds)
In your code, instead of dividing seconds by 60, you should subtract it. If your total time was 300 secs, in first loop, you will have seconds updated to 5 while minutes will be updated to 1.

Countdown to tomorrow date in javascript?

I have this code:
And its not working. It's always showing -7 hours, it should count to next 7:00.
How to do this?
function ShowTime() {
var now = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var hrs = 7-now.getHours();
var mins = 60-now.getMinutes();
var secs = 60-now.getSeconds();
timeLeft = "" +hrs+' hours '+mins+' minutes '+secs+' seconds';
$("#countdown").html(timeLeft);
}
var countdown;
function StopTime() {
clearInterval(countdown);
}
setInterval(ShowTime ,1000);
getHours(); The getHours() method returns the hour (from 0 to 23) of the specified date and time.
So change your code 7-now.getHours(); returns negative when the time is past 7

Categories

Resources