Get elapsed time in Javascript between two timestamps - javascript

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.

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>

Timer every hour but starting from 1 minute

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

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

Date difference in PHP

I'm trying to get a countdown system on my site that countdown only 24hrs from the time of registration.
The idea is after registration, a subscriber has 24hrs to make payment after which he will be blocked. I have the registration time already in my database but i'm stuck with the countdown. I've tried several help online but I don't seem to be getting it right.
The javascript is set to work with the seconds remaining for the user to make payment var count = '86400'; but i want to use php to calculate from the time registered till the current time how long he has left to register, so that when i refresh the page, it doesn't start from the current time left. So i did this var count = <?php echo strtotime($row_rsPH['date'])-time(); ?>;
<script type="text/javascript">
var count = <?php echo strtotime($row_rsPH['date'])-time(); ?>;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + seconds; // watch for spelling
}
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
</script>
<p>Time Left to make payment: <span id='timer'></span></p>
I used a countdown sample here http://www.hashemian.com/tools/javascript-countdown.htm and under TargetDate i used this php code
<?php
$date = date_create($row_rsPH['date']);
date_add($date, date_interval_create_from_date_string('1 days'));
echo date_format($date, 'Y-m-d h:i A');
?>
Hope this helps someone else

Recursive countdown timer

I'm trying to create a javascript counter that starts at 25 minutes and ends at 0. the idea is to show the minutes/seconds as a countdown clock on the page (my target div is called 'txt'). But I'm not getting my desired result - the timer does not subtract each time the function is run (every ms). Any ideas on where I'm going wrong? Code is below:
function countdown() {
var target = 1500000; // 25 mins
var current = 1000; // 0 secs
for (var i=0; i<5; i++) {
var diff = target-current; // calculates the 25 minutes
var min = Math.floor(diff/1000/60); //gets mins
var sec = (diff/1000) % 60; // gets secs
current = current+1000;
document.getElementById("txt").innerHTML = min + ":" + sec;
var t = setTimeout(countdown, 2500);}
}
}
You need to define current outside of your function. Currently you are resetting it to 1000 every time the function is run.
here you go:
var target = 1500000; // 25 mins
var current = 0; // 0 secs
function countdown() {
current += 1000;
var diff = target-current; // calculates the 25 minutes
var min = Math.floor(diff/1000/60); //gets mins
var sec = (diff/1000) % 60; // gets secs
document.getElementById("txt").innerHTML = min + ":" + sec;
if (diff > 0)
setTimeout(countdown, 1000);
}
countdown();
JSFiddle with running example: https://jsfiddle.net/epcmw0uc/5/

Categories

Resources