Recurring Countdown Timer - Every 10 Minutes Based On Actual Time - javascript

I am trying to create a countdown timer that will continually count down to the nearest 10 minute interval of real time. So if a user lands on the page at 4:01pm it would count down 9:00 and then reset when it hits 0. But the time would always be relative to actual time.
This is what I have so far:
<p id="timer"></p>
<script>
var start = Date.now(),
r = document.getElementById("timer");
(function f() {
var diff = Date.now() - start,
ns = ((6e5 - diff) / 1000) >> 0,
m = (ns / 60) >> 0,
s = ns - m * 60;
r.textContent =
m + ":" + (("" + s).length > 1 ? "" : "0") + s + " minutes";
if (diff > 6e5) {
start = Date.now();
}
setTimeout(f, 1000);
})();
</script>
Here is a codepen of my code working
https://codepen.io/gvolkerding/pen/jOOmygQ
This only counts down 10 minutes from the time that the user lands on the page, but I can't figure out how to modify it to look for the next 10 minute mark and then count down to it. Any help would be greatly appreciated

Not the most efficient way to handle this, but it should ensure that the countdown stays consistent with the client machine clock. Just get the minutes and seconds of the current datetime and then calculate the remainder up to the next 10 minute mark.
const timer = document.getElementById('timer');
const countdown = () => {
const dt = new Date();
let m = dt.getMinutes();
let s = dt.getSeconds();
// minutes remaining until next 10 minute mark
m = s ? 9 - (m % 10) : 10 - (m % 10);
// seconds remaining until next minute mark
if (s) {
s = 60 - s;
}
timer.textContent = `${m}:${s < 10 ? '0' + s : s} minutes`;
};
setInterval(countdown, 1000);
<p id="timer"></p>

Related

how to create a countdown that repeats every 48 or 72 hours

I'm trying to create a countdown that repeats every 24, 48 or 72 hours at midnight without moment.js
For example (example for 48 hours):
10-12-22 00:00 -> start countdown -> 47:59:59
11-12-22 22:30 -> countdown = 1:30:00
12-12-22 00:00 -> the countdown restart -> 47:59:59
I try solution only for 24 hours
I try this:
setInterval(function time() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if ((min + '').length == 1) {
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if ((sec + '').length == 1) {
sec = '0' + sec;
},
1000);
There are a huge number of questions and answers already about timers and countdowns. Pick one.
The only point of interest here is that it should to restart when the remainder gets to zero, e.g.:
// Counts down period milliseconds, then restarts
function timer(period) {
let start = new Date();
let z = n => ('0'+n).slice(-2);
let zz = n => ('00'+n).slice(-3);
let f = ms => {
let day = (ms / 8.64e7) | 0;
let hr = (ms % 8.64e7) / 3.6e6 | 0;
let min = (ms % 3.6e6) / 6e4 | 0;
let sec = (ms % 6e4) /1e3 | 0;
let mil = (ms % 1e3);
return `${day} days, ${z(hr)}:${z(min)}:${z(sec)}.${zz(mil)}`;
}
setInterval(() => {
console.log(f(period - (Date.now() - start) % period));
}, 1000);
}
timer(1000*5);
Format the output however you want, maybe floor the seconds and ditch the milliseconds.
BTW, setInterval is not a good way to run a timer. Use successive calls to setTimelout with the lag set to about 10ms longer than the time to the next full second, minute or whatever. That way it won't be seen to miss a second (which happens with setInteval because it may slowly drift, as can be seen in the ms part of the above, there is always at least 1e3 ms between logs, usually more and sometimes a lot more, depending on how busy the system is with other tasks).
I don't really get the question but perhaps try setInterval?
//this will log to console after 2 days
setInterval(() => {
console.log("Ding Dong");
},
2*24*60*60*1000);

How to modify count down timer in javascript code

is there a way to manipulate a count-down timer to change the time of the countdown to zero much faster? here is the code for the:
function CalcTimePercent(i, lastpayment, nextpayment, t, p) {
var time = nextpayment - t;
var hour = parseInt(time / 3600);
if ( hour < 1 ) hour = 0;
time = parseInt(time - hour * 3600);
if ( hour < 10 ) hour = '0'+hour;
var minutes = parseInt(time / 60);
if ( minutes < 1 ) minutes = 0;
time = parseInt(time - minutes * 60);
if ( minutes < 10 ) minutes = '0'+minutes;
var seconds = time;
if ( seconds < 10 ) seconds = '0'+seconds;
timer = hour+':'+minutes+':'+seconds;
document.getElementById('deptimer'+i).innerHTML = timer;
if(timer == "00:00:00") {
top.location.href='';
}
if(timer == "00:00:0-64") {
top.location.href='';
}
t = t + 1;
setTimeout("CalcTimePercent("+i+", "+lastpayment+", "+nextpayment+", "+t+", "+p+")",1000);
}
The easiest way I can think of is using JavaScript's Date class. You would get the time the timer would end, as well as the current time, and constantly check the difference between the two. Here is how you would do that in your case:
let timer = null;
function runTimer(time) {
clearInterval(timer);
timer = setInterval(() => {
const timer = new Date(time.getTime() - new Date().getTime()); // Get difference between now and the end time
const timerText = `${timer.getUTCHours()}h ${timer.getMinutes()}m ${timer.getSeconds()}s`; // Generate a stylised version of the text
// document.getElementById("ELEMENT_ID").textContent = timerText; // Apply the stylised text to the timer element
console.log(timerText); // Apply the stylised text to the timer element
}, 1000); // Run this every 1000ms (1 second)
}
runTimer(new Date(Date.now() + 10 * 60000)); // Start timer for 10 minutes in the future
setTimeout(() => { // Wait 5 seconds
runTimer(new Date(Date.now() + 15 * 60000)); // Update timer for 15 minutes in the future
}, 5000);
The limitation of this method include the fact that it only supports times up to 24 hours. Any time over that will loop back (A timer of 27 hours will show up as "2h 0m 0s").

Countdown timer is lagging behind

I am trying to create countdown timer between 2 dates but the time is lagging behind after a while.
My PHP backend returns the difference between current time and X time in the future, for example current time and 2 hours in advance. This difference is passed to my HTML frontent in a .countdown class in the following format 03:20:15 which I use a javascript function to countdown the difference. Here is my function:
$(".countdown").each(function() {
var $e = $(this);
var interval = setInterval(function() {
var timer2 = $e.html();
var timer = timer2.split(':');
var hours = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
hours = (minutes < 0) ? --hours : hours;
if(hours < 0) {
clearInterval(interval);
window.location.reload();
} else {
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hours = (hours < 10) ? '0' + hours : hours;
$e.html(hours + ':' + minutes + ':' + seconds);
}
}, 1000);
});
The code works as expected but after a few minutes, lets say 2-3 minutes, if you refresh the page or open it in a new window you will see that the countdown timer was lagging behind by seconds/minutes. Does someone know what Im doing wrong?
You should compute the difference between (new Date()) and the target date. Use that difference and format new HTML string instead of parsing it to a hour, minutes, seconds value for decrementing.
details
The setInterval api specs suggest that delays due to CPU load, other tasks, etc, are to be expected.
https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
Your handler is called at approximately equal intervals while you consider them to be exact. At first iteration the actual time may differ from a planed time by some small amount (let say 4ms). Yet you are changing your counter by 1000 ms. As many more iterations passed this difference accumulates and become noticeable. A few minutes is enough to make this happens.
If you, on the other hand, pre-compute the target date-time value and will use the difference between current time and the target time your code will not be sensible to api inexactness.
$(".countdown").each(function () {
var $e = $(this);
const totalSeconds = (dt) => Math.floor(dt.valueOf() / 1000);
const f1 = (timer2) => {
var timer = timer2.split(':');
var tdt = new Date().setHours(
parseInt(timer[0]) + tdt.getHours(),
parseInt(timer[1]) + tdt.getMinutes(),
parseInt(timer[2]) + tdt.getSeconds());
return totalSeconds(tdt);
};
const targetTime = f1($e.html());
setInterval(function () {
var timeSpan = targetTime - totalSeconds(new Date());
if (timeSpan < 0) {
window.location.reload();
} else {
var seconds = timeSpan % 60;
var totalMinutes = Math.floor(timeSpan / 60);
var minutes = totalMinutes % 60;
var hours = Math.floor(totalMinutes / 60);
$e.html(hours + ':' + minutes + ':' + seconds);;
}
}, 1000);
});
see also:
https://jsfiddle.net/8dygbo9a/1/

Showing milliseconds in a timer html [duplicate]

This question already has answers here:
Adding milliseconds to timer in html
(2 answers)
Closed 8 years ago.
How do i show a countdown timer in html?
Current code:
var count=6000;
var counter=setInterval(timer, 1);; //1000 will run it every 1 second
function timer(){
count=count-1;
if (count <= 0){
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " milliseconds"; // watch for spelling
}
Converting seconds to ms
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
How would i call out the timer?
still shows the timer as ms. i want it to show up as 99:00 seconds instead of 9900 milliseconds.
Thanks
You can do something like this:
var expires = new Date();
expires.setSeconds(expires.getSeconds() + 60); // set timer to 60 seconds
var counter = setInterval(timer, 1);
function timer() {
var timeDiff = expires - new Date();
if (timeDiff <= 0) {
clearInterval(counter);
document.getElementById("timer").innerHTML = "00:00";
return;
}
var seconds = new Date(timeDiff).getSeconds();
var milliSeconds = (new Date(timeDiff).getMilliseconds() / 10).toFixed(0);
var seconds = seconds < 10 ? "0" + seconds : seconds;
var milliSeconds = milliSeconds < 10 ? "0" + milliSeconds : milliSeconds;
document.getElementById("timer").innerHTML = seconds + ":" + milliSeconds; // watch for spelling
}
Here i set the start time from the javascript Date() function and then calculate the difference from current time in the timer() function.
Check it out here: JSFiddle
If it's JavaScript and has to do with Time I use moment.js
http://momentjs.com
Moment defaults to milliseconds as it's first parameter:
moment(9900).format("mm:ss"); Is 9 seconds, displayed as: 00:09
http://plnkr.co/edit/W2GixF?p=preview
Here's an actually accurate timer (in that it actually shows the correct amount of time left). setInterval will never call every 1 ms regardless of what you ask for because the actually resolution isn't that high. Nor can you rely on consistency because it's not running in a real-time environment. If you want to track time, compare Date objects:
var count=60000;
var start = new Date();
var counter=setInterval(timer, 1); //1000 will run it every 1 second
function timer(){
var left = count - (new Date() - start);
if (left <= 0){
clearInterval(counter);
document.getElementById("timer").innerHTML = msToTime(0) + " seconds";
return;
}
document.getElementById("timer").innerHTML = msToTime(left) + " seconds"; // watch for spelling
}
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
return s + ':' + pad(ms, 3);
}
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
<div id='timer'></div>
Borrowing from #Cheery's fiddle as a starting point.

javascript countdown to next real 5 minutes

I need to create a javascript timer that will count down to the next 5 minutes.
For example let's say the time is 00:07:30, the time will say 02:30
if the time is 15:42:00 the timer will say 03:00
I can't really think of any good way to du this.
thank you.
There are many ways to do this. My idea is to find out the reminder of current time divide by five minutes (300 seconds).
Demo : http://jsfiddle.net/txwsj/
setInterval(function () {
var d = new Date(); //get current time
var seconds = d.getMinutes() * 60 + d.getSeconds(); //convet current mm:ss to seconds for easier caculation, we don't care hours.
var fiveMin = 60 * 5; //five minutes is 300 seconds!
var timeleft = fiveMin - seconds % fiveMin; // let's say now is 01:30, then current seconds is 60+30 = 90. And 90%300 = 90, finally 300-90 = 210. That's the time left!
var result = parseInt(timeleft / 60) + ':' + timeleft % 60; //formart seconds back into mm:ss
document.getElementById('test').innerHTML = result;
}, 500) //calling it every 0.5 second to do a count down
Instead you could try using window.setInterval() like this:
window.setInterval(function(){
var time = document.getElementById("secs").innerHTML;
if (time > 0) {
time -= 1;
} else {
alert ("times up!");
//or whatever you want
}
document.getElementById("secs").innerHTML = time;
}, 1000);
const startMinutes = 1
let time = startMinutes * 60
const updateCountDown = () => {
const t = setInterval(() => {
const minutes = Math.floor(time / 60)
const seconds = time % 60
const result = `${parseInt(minutes)}:${parseInt(seconds)}`
document.getElementById('test').innerHTML = result
time--
if (minutes === 0 && seconds === 0) {
clearInterval(t)
}
}, 1000)
}
If you want to do a timer on your webpage, you can try to use something like this:
<html>
<head>
<script type="text/javascript">
var now = new Date().getTime();
var elapsed = new Date().getTime() - now;
document.getElementById("timer").innerHtml = elapsed;
if (elapsed > 300000 /*milliseconds in 5 minutes*/) {
alert ("5 minutes up!");
//take whatever action you want!
}
</script>
</head>
<body>
<div id="timer"></div>
</body>
</html>

Categories