How to modify count down timer in javascript code - javascript

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").

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);

Adding time on button click to a count down timer

Im creating a countdown timer which starts at 3mins and 30secs.
When the timer reaches 0 the initial 3:30 timer will be repeated.
This happens until the user presses a button, which will add 1:45 to the timer and pause the timer until the user decides to resume the timer from the new value. Eg ( 3:30 + 1:45 = 5:15).
Now I have got the first 2 step to work with my current code, but I'm having a lot of issues with the 3rd part. Once the user clicks the add 1.45 button the count works, but only up until a certain point. After this point it will start to display a negative integer.
I'm sure there is an easier way to write this code. I have really overcomplicated this. Any suggestions would be appreciated.
//Define vars to hold time values
let startingMins = 3.5;
let time = startingMins * 60;
//define var to hold stopwatch status
let status = "stopped";
//define var to holds current timer
let storeTime = null;
//define Number of sets
let setNum = 1;
//Stop watch function (logic to determin when to decrement each value)
function stopwatch () {
minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
storeTimer = minutes + ":" + seconds; //Store time in var
storeTime = minutes + "." + seconds; //Store time in var
//Display updated time values to user
document.getElementById("display").innerHTML = storeTimer;
time--;
// When timer reachers 0 secs the inital 3:30 countdown will begin again.
if (time <= 0) {
startingMins = 3.5;
time = startingMins * 60;
minutes = Math.floor(time / 60);
seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
setNum++;
//console.log(setNum);
}
}
function StartStop() {
if(status === "stopped") {
//start watch
interval = window.setInterval(stopwatch, 100);
var startButton = document.getElementById("start");
document.getElementById("start").innerHTML = "Pauce";
//startButton.style.display = "none"
status = "start";
//console.log(time);
}
else {
window.clearInterval(interval);
document.getElementById("start").innerHTML = "Start";
status = "stopped";
console.log(storeTime);
}
}
function pauceAdd () {
if(status === "stopped") {
//start watch
interval = window.setInterval(stopwatch, 1000);
var zukButton = document.getElementById("pauceAdd");
status = "start";
}
else {
window.clearInterval(interval);
status = "stopped";
console.log("store time " + storeTime);
let time = +storeTime + +1.45; //store time is 3.30 adding 4.75
console.log("store time2 " + time); // correct result 4.75
minutes = Math.floor(time);/// convert time from Mins (4.75) to seconds (475)
let seconds = time % 60; // 5
if (seconds < 60 ) { // if the Stored time is greater than 60 secs add 1 minute to the timer
minutes++;
seconds = seconds * 100;
console.log("secs updated = " + seconds ); // seconds updated (475)
if (seconds <= 460) {
seconds = Math.floor(seconds - 460);
console.log("seconds 2 == " + seconds)
}
else if (seconds > -60) { // Stuck here
seconds = seconds + 60;// Stuck here
}// Stuck here
else {
seconds = Math.floor(seconds - 460);
console.log("seconds 2 = " + seconds)
}
}
if (seconds < 1) {
seconds = seconds + 60;
minutes = minutes - 1;
}
seconds = seconds < 10 ? + seconds : seconds;
console.log("mins updated = " + minutes + "__________________________-");
//Display updated time values to user
document.getElementById("display").innerHTML = minutes + ":" + seconds;
}
}
function reset () {
//window.clearInterval(storeTime);
window.clearInterval(interval);
startingMins = 3.5;
time = startingMins * 60;
minutes = Math.floor(time / 60);
seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
status = "stopped";
setNum = 1;
var startButton = document.getElementById("start");
startButton.style.display = "inline-block";
document.getElementById("display").innerHTML = "3:30";
document.getElementById("start").innerHTML = "Start";
}
I might have taken the requirements a bit too literally:
Im creating a countdown timer which starts at 3mins and 30secs.
When the timer reaches 0 the initial 3:30 timer will be repeated.
This happens until the user presses a button, which will add 1:45 to the timer and pause the timer until the user decides to resume the
timer from the new value. Eg ( 3:30 + 1:45 = 5:15).
There's a trick to countdown timers. You have to use timestamps to find out how much time ACTUALLY elapsed. You can't trust that your interval will fire exactly every second. In fact, it almost always fires a bit later (in my tests, about 2-3 milliseconds, but I was logging to the console as well, so that might have skewed the test).
let interval, timestamp;
let countdown = 210000;
document.addEventListener("DOMContentLoaded", () => {
document
.querySelector("button")
.addEventListener("click", (event) => toggleState(event.target));
});
function toggleState({ dataset }) {
timestamp = Date.now();
if (dataset.state == "running") {
clearInterval(interval);
countdown += 105000;
updateDisplay(dataset, "paused");
} else {
interval = setInterval(() => updateCountdown(dataset), 100);
updateDisplay(dataset, "running");
}
}
function updateCountdown(dataset) {
const now = Date.now();
countdown -= now - timestamp;
if (countdown <= 0) countdown = 210000;
timestamp = now;
updateDisplay(dataset, "running");
}
function updateDisplay(dataset, label) {
dataset.state = label;
dataset.time = `(${new Date(countdown).toISOString().slice(14, 19)})`;
}
button::before {
content: attr(data-state);
}
button::after {
content: attr(data-time);
padding-left: 0.5em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<button data-state="stopped" data-time="(03:30)"></button>

Recurring Countdown Timer - Every 10 Minutes Based On Actual Time

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>

Find elapsed time in javascript

I'm new to JavaScript and I'm trying to write a code which calculates the time elapsed from the time a user logged in to the current time.
Here is my code:-
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var markMinutes = markDate.getMinutes();
var markSeconds = markDate.getSeconds();
var currDate = new Date();
var currMinutes = currDate.getMinutes();
var currSeconds = currDate.getSeconds();
var minutes = currMinutes - markMinutes;
if(minutes < 0) { minutes += 60; }
var seconds = currSeconds - markSeconds;
if(seconds < 0) { seconds += 60; }
if(minutes < 10) { minutes = "0" + minutes; }
if(seconds < 10) { seconds = "0" + seconds; }
var hours = 0;
if(minutes == 59 && seconds == 59) { hours++; }
if(hours < 10) { hours = "0" + hours; }
var timeElapsed = hours+':'+minutes+':'+seconds;
document.getElementById("timer").innerHTML = timeElapsed;
setTimeout(function() {updateClock()}, 1000);
}
The output is correct upto 00:59:59 but after that that O/P is:
00:59:59
01:59:59
01:59:00
01:59:01
.
.
.
.
01:59:59
01:00:00
How can I solve this and is there a more efficient way I can do this?
Thank you.
No offence, but this is massively over-enginered. Simply store the start time when the script first runs, then subtract that from the current time every time your timer fires.
There are plenty of tutorials on converting ms into a readable timestamp, so that doesn't need to be covered here.
var start = Date.now();
setInterval(function() {
document.getElementById('difference').innerHTML = Date.now() - start;
// the difference will be in ms
}, 1000);
<div id="difference"></div>
There's too much going on here.
An easier way would just be to compare markDate to the current date each time and reformat.
See Demo: http://jsfiddle.net/7e4psrzu/
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var currDate = new Date();
var diff = currDate - markDate;
document.getElementById("timer").innerHTML = format(diff/1000);
setTimeout(function() {updateClock()}, 1000);
}
function format(seconds)
{
var numhours = parseInt(Math.floor(((seconds % 31536000) % 86400) / 3600),10);
var numminutes = parseInt(Math.floor((((seconds % 31536000) % 86400) % 3600) / 60),10);
var numseconds = parseInt((((seconds % 31536000) % 86400) % 3600) % 60,10);
return ((numhours<10) ? "0" + numhours : numhours)
+ ":" + ((numminutes<10) ? "0" + numminutes : numminutes)
+ ":" + ((numseconds<10) ? "0" + numseconds : numseconds);
}
markPresent();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="timer"></div>
Here is a solution I just made for my use case. I find it is quite readable. The basic premise is to simply subtract the timestamp from the current timestamp, and then divide it by the correct units:
const showElapsedTime = (timestamp) => {
if (typeof timestamp !== 'number') return 'NaN'
const SECOND = 1000
const MINUTE = 1000 * 60
const HOUR = 1000 * 60 * 60
const DAY = 1000 * 60 * 60 * 24
const MONTH = 1000 * 60 * 60 * 24 * 30
const YEAR = 1000 * 60 * 60 * 24 * 30 * 12
// const elapsed = ((new Date()).valueOf() - timestamp)
const elapsed = 1541309742360 - timestamp
if (elapsed <= MINUTE) return `${Math.round(elapsed / SECOND)}s`
if (elapsed <= HOUR) return `${Math.round(elapsed / MINUTE)}m`
if (elapsed <= DAY) return `${Math.round(elapsed / HOUR)}h`
if (elapsed <= MONTH) return `${Math.round(elapsed / DAY)}d`
if (elapsed <= YEAR) return `${Math.round(elapsed / MONTH)}mo`
return `${Math.round(elapsed / YEAR)}y`
}
const createdAt = 1541301301000
console.log(showElapsedTime(createdAt + 5000000))
console.log(showElapsedTime(createdAt))
console.log(showElapsedTime(createdAt - 500000000))
For example, if 3000 milliseconds elapsed, then 3000 is greater than SECONDS (1000) but less than MINUTES (60,000), so this function will divide 3000 by 1000 and return 3s for 3 seconds elapsed.
If you need timestamps in seconds instead of milliseconds, change all instances of 1000 to 1 (which effectively multiplies everything by 1000 to go from milliseconds to seconds (ie: because 1000ms per 1s).
Here are the scaling units in more DRY form:
const SECOND = 1000
const MINUTE = SECOND * 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const MONTH = DAY * 30
const YEAR = MONTH * 12
We can also use console.time() and console.timeEnd() method for the same thing.
Syntax:
console.time(label);
console.timeEnd(label);
Label:
The name to give the new timer. This will identify the timer; use the same name when calling console.timeEnd() to stop the timer and get the time output to the console.
let promise = new Promise((resolve, reject) => setTimeout(resolve, 400, 'resolved'));
// Start Timer
console.time('x');
promise.then((result) => {
console.log(result);
// End Timer
console.timeEnd('x');
});
You can simply use performance.now()
Example:
start = performance.now();
elapsedTime = performance.now() - start;
var hours = 0;
if(minutes == 59 && seconds == 59)
{
hours = hours + 1;
minutes = '00';
seconds == '00';
}
I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.
I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be added.
(function(w){
var timeStart,
timeEnd,
started = false,
startTimer = function (){
this.timeStart = new Date();
this.started = true;
},
getPartial = function (end) {
if (!this.started)
return 0;
else {
if (end) this.started = false;
this.timeEnd = new Date();
return (this.timeEnd - this.timeStart) / 1000;
}
},
stopTime = function () {
if (!this.started)
return 0;
else {
return this.getPartial(true);
}
},
restartTimer = function(){
this.timeStart = new Date();
};
w.Timer = {
start : startTimer,
getPartial : getPartial,
stopTime : stopTime,
restart : restartTimer
};
})(this);
Start
Partial
Stop
Restart
What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):
var trace = console.log
function elapsed(op) {
this.op = op
this.t0 = Date.now()
}
elapsed.prototype.show = function() {
trace.apply(null, [this.op, 'msec', Date.now() - this.t0, ':'].concat(Array.from(arguments)))
}
to be used - for instance:
function debug_counters() {
const e = new elapsed('debug_counters')
const to_show = visibleProducts().length
e.show('to_show', to_show)
}

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