Find elapsed time in javascript - 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)
}

Related

How to make Javascript countdown for 24 hours and fade out a div element after 24 Hours?

var date = new Date;
var s = date.getSeconds();
var m = date.getMinutes();
var h = date.getHours();
setTimeout(function () {
$('#offer1').fadeOut('fast');
$('#remainingTime').fadeOut('fast');
}, 8640000);
function Timer(duration, display) {
var timer = duration, hours, minutes, seconds;
setInterval(function () {
hours = parseInt((timer / 3600) % 24, 10)
minutes = parseInt((timer / 60) % 60, 10)
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(parseInt(hours-h) + ":" + parseInt(minutes-m) + ":" + parseInt(seconds-s));
--timer;
}, 1000);
}
jQuery(function ($) {
var twentyFourHours = 24 * 60 * 60;
var display = $('#remainingTime');
Timer(twentyFourHours, display);
});
var i =$("remainingTime").textContent;
console.log(i);
<div class="ml-2">Time Remaining <span id="remainingTime">24:00:00</span></div>
<div id="offer1">asdf</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
Here, I've made a timer which says how much time is left for 24 Hours.
But it's showing Hours, Minutes and seconds in negative value for seconds after a minute and negative value for minutes after an Hour.
I need the both div elements ("offer1" and "remainingTime") should fade out after 24 hours timer.
By using the current Date and getTime() I should show the time remaining
Here is the JSFiddle Link https://jsfiddle.net/Manoj07/d28khLmf/2/...
Thanks for everyone who tried to help me. And here is the answer
https://jsfiddle.net/Manoj07/1fyb4xv9/1/
Hello this code works for me
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<div class="ml-2">Time Remaining <span id="remainingTime"></span></div>
<div id="offer1">asdf</div>
<script>
// this code set time to 24 hrs
var timer2 = "24:00:00";
/*
if you want to get timer from localstorage
var session_timer = localStorage.getItem('timer');
if(session_timer){
console.log('timer',session_timer);
timer2 = session_timer;
}
*/
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
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);
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hours = (hours < 10) ? '0' + hours : hours;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 10) ? minutes : minutes;
timer2 = hours+ ':' +minutes + ':' + seconds;
if(hours <= 0 && minutes == 0 && seconds == 0){
// if you want to delete it on local storage
// localStorage.removeItem('timer');
console.log('finish')
// fade out div element
$( "#offer1" ).fadeOut( "slow", function() {
// Animation complete.
});
}
else{
$('#remainingTime').html(timer2);
// if you want to save it on local storage
// localStorage.setItem('timer', timer2);
}
}, 1000);
</script>
createCountdown returns a countdown object with two methods: start and stop.
A countdown has a to date, an onTick callback, and a granularity.
The granularity is the frequency at which the onTick callback is invoked. So if you set a granularity of 1000ms, then the countdown will only tick once a second.
Once the difference between now and to is zero, the onComplete callback is called, and this hides the DOM node.
This solution uses requestAnimationFrame which will have a maximum resolution of about 16 milliseconds. Given that this is the maximum speed that the screen is updated, this is fine for our purposes.
const $ = document.querySelector.bind(document)
const now = Date.now
const raf = requestAnimationFrame
const caf = cancelAnimationFrame
const defaultText = '--:--:--:--'
const createCountdown = ({ to, onTick, onComplete = () => {}, granularityMs = 1, rafId = null }) => {
const start = (value = to - now(), grain = null, latestGrain = null) => {
const tick = () => {
value = to - now()
if(value <= 0) return onTick(0) && onComplete()
latestGrain = Math.trunc(value / granularityMs)
if (grain !== latestGrain) onTick(value)
grain = latestGrain
rafId = raf(tick)
}
rafId = raf(tick)
}
const stop = () => caf(rafId)
return { start, stop }
}
const ho = (ms) => String(Math.trunc((ms/1000/60/60))).padStart(2, '0')
const mi = (ms) => String(Math.trunc((ms%(1000*60*60))/60000)).padStart(2, '0')
const se = (ms) => String(Math.trunc((ms%(1000*60))/1000)).padStart(2, '0')
const ms = (ms) => String(Math.trunc((ms%(1000)))).padStart(3, '0')
const onTick = (value) => $('#output').innerText = `${ho(value)}:${mi(value)}:${se(value)}:${ms(value)}`
const onComplete = () => $('#toFade').classList.add('hidden')
const to = Date.now() + (2 * 60 * 1000)
const { start, stop } = createCountdown({ to, onTick, onComplete })
$('button#start').addEventListener('click', start)
$('button#stop').addEventListener('click', () => (stop(), $('#output').innerText = defaultText))
div#toFade {
opacity: 1;
transition: opacity 5s linear 0s;
}
div#toFade.hidden {
opacity: 0;
}
div {
padding: 20px;
}
<button id="start">Start</button>
<button id="stop">Stop</button>
<div id="output">--:--:--:--</div>
<div id="toFade">This is the element to fade out.</div>
See https://www.w3schools.com/howto/howto_js_countdown.asp for the code used to create a countdown timer
See how to get tomorrow's date: JavaScript, get date of the next day
// Set the date we're counting down to
const today = new Date()
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = tomorrow - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
hours = ("00" + hours).slice(-2);
minutes = ("00" + minutes).slice(-2);
seconds = ("00" + seconds).slice(-2);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = 'Time Remaining: '+hours + ":"
+ minutes + ":" + seconds;
// If the count down is over, hide the countdown
if (distance < 0) {
$("#demo").hide();
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
</body>
</html>

Javascript Count Up Timer

I am trying to make a javascript timer that when initiated, starts counting up. The timer is just a visual reference from when a start button is clicked to when the end button is clicked.
I found a plugin online which works perfectly for counting down but I am trying to modify it to count up.
I hard coded a date way in the future. I am now trying to get the timer to start counting up to that date. This will be reset every time the start button is clicked.
This is the function I am working with. it works perfectly to count down but I cant figure out how to reverse it.
I thought it was something with how the differece was calculated but I believe it actually happens in the //calculate dates section.
Is there an easy way to reverse this math and have it count up instead?
Fiddle: http://jsfiddle.net/xzjoxehj/
var currentDate = function () {
// get client's current date
var date = new Date();
// turn date to utc
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// set new Date object
var new_date = new Date(utc + (3600000*settings.offset))
return new_date;
};
function countdown () {
var target_date = new Date('12/31/2020 12:00:00'), // Count up to this date
current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - target_date;
// if difference is negative than it's pass the target date
if (difference > 0) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
var interval = setInterval(countdown, 1000);
};
JSFiddle
var original_date = currentDate();
var target_date = new Date('12/31/2020 12:00:00'); // Count up to this date
var interval;
function resetCountdown() {
original_date = currentDate();
}
function stopCountdown() {
clearInterval(interval);
}
function countdown () {
var current_date = currentDate(); // get fixed current date
// difference of dates
var difference = current_date - original_date;
if (current_date >= target_date) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
//
};
// start
interval = setInterval(countdown, 1000);
};
This OP already has an answer but that has issue with timezone , so this answer.
DownVoters care to comment.
Try this. Fiddle
var TargetDate = new Date('2015', '08', '04', 11, 11, 30) // second parameter is month and it is from from 0-11
$('#spanTargetDate').text(TargetDate);
$('#spanStartDate').text(new Date());
var Sec = 0,
Min = 0,
Hour = 0,
Days = 0;
var counter = setInterval(function () {
var CurrentDate = new Date()
$('#spanCurrentDate').text(CurrentDate);
var Diff = TargetDate - CurrentDate;
if (Diff < 0) {
clearInterval(counter);
$('#timer').text('Target Time Expired. test in fiddle')
} else {
++Sec;
if (Sec == 59) {
++Min;
Sec = 0;
}
if (Min == 59) {
++Hour;
Min = 0;
}
if (Hour == 24) {
++Days;
Hour = 0;
}
if (Sec <= Diff) $('#timer').text(pad(Days) + " : " + pad(Hour) + " : " + pad(Min) + " : " + pad(Sec));
}
}, 1000);
function pad(number) {
if (number <= 9) {
number = ("0" + number).slice(-4);
}
return number;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Target Time - <span id="spanTargetDate"></span>
<br/>
<br/>Start Time - <span id="spanStartDate"></span>
<br/>
<br/>Current Time - <span id="spanCurrentDate"></span>
<br/>
<br/>Timer (DD:HH:MM:SS) - <span id="timer"></span>
<br/>
<br/>

calculate time difference between two date in HH:MM:SS javascript

I have created one timer application in javascript.
Firstly it takes the current UTC date to init timer with some reference. here's the code
on_timer: function(e) {
var self = this;
if ($(e.target).hasClass("pt_timer_start")) {
var current_date = this.get_current_UTCDate();
this.project_timesheet_db.set_current_timer_activity({date: current_date});
this.start_interval();
this.initialize_timer();
this.$el.find(".pt_timer_start,.pt_timer_stop").toggleClass("o_hidden");
Now, Once timer is started and after some time span timer has some elapsed time with reference to above on_timer: function(e) function.
This function is
start_interval: function() {
var timer_activity = this.project_timesheet_db.get_current_timer_activity();
var self = this;
this.intervalTimer = setInterval(function(){
self.$el.find(".pt_duration").each(function() {
var el_hour = $(this).find("span.hours");
var el_minute = $(this).find("span.minutes");
var minute = parseInt(el_minute.text());
if(minute >= 60) {
el_hour.text(_.str.sprintf("%02d", parseInt(el_hour.text()) + 1));
minute = 0;
}
el_minute.text(_.str.sprintf("%02d", minute));
var el_second = $(this).find("span.seconds");
var seconds = parseInt(el_second.text()) + 1;
if(seconds > 60) {
el_minute.text(_.str.sprintf("%02d", parseInt(el_minute.text()) + 1));
seconds = 0;
}
el_second.text(_.str.sprintf("%02d", seconds));
});
}, 1000);
},
Now, considering el_hour, el_minute, el_seconds How to can i count time difference between init time and current timer value in HH:MM:SS manner.
thanks in advance for help
To convert H:M:S to seconds, you can use a simple function like:
// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
var b = s.split(':');
return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}
Then to convert seconds back to HMS:
// Convert seconds to hh:mm:ss
// Allow for -ve time values
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0? '-':'';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}
var a = '01:43:28';
var b = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(a) - hmsToSeconds(b))); // -10:39:18
console.log(secondsToHMS(hmsToSeconds(b) - hmsToSeconds(a))); // 10:39:18
You may want to abbreviate the function names to say:
toHMS(toSec(a) - toSec(b)); // -10:39:18
Note that this doesn't cover where the time may cross a daylight saving boundary. For that you need fully qualified dates that include the year, month and day. Use the values to create date objects, find the difference, convert to seconds and use the secondsToHMS function.
Edit
The question title mentions dates, however the content only seems to mention strings of hours, minutes and seconds.
If you have Date objects, you can get the difference between them in milliseconds using:
var diffMilliseconds = date0 - date1;
and convert to seconds:
var diffSeconds = diffMilliseconds / 1000;
and present as HH:MM:SS using the secondsToHMS function above:
secondsToHMS((date0 - date1) / 1000);
e.g.
var d0 = new Date(2014,10,10,1,43,28);
var d1 = new Date(2014,10,10,12,22,46);
console.log( secondsToHMS((d0 - d1) / 1000)); // -10:39:18
I think there is a simpler solution.
function dateDiffToString(a, b){
// make checks to make sure a and b are not null
// and that they are date | integers types
diff = Math.abs(a - b);
ms = diff % 1000;
diff = (diff - ms) / 1000
ss = diff % 60;
diff = (diff - ss) / 60
mm = diff % 60;
diff = (diff - mm) / 60
hh = diff % 24;
days = (diff - hh) / 24
return days + ":" + hh+":"+mm+":"+ss+"."+ms;
}
var today = new Date()
var yest = new Date()
yest = yest.setDate(today.getDate()-1)
console.log(dateDiffToString(yest, today))
const dateDiffToString = (a, b) => {
let diff = Math.abs(a - b);
let ms = diff % 1000;
diff = (diff - ms) / 1000;
let s = diff % 60;
diff = (diff - s) / 60;
let m = diff % 60;
diff = (diff - m) / 60;
let h = diff;
let ss = s <= 9 && s >= 0 ? `0${s}` : s;
let mm = m <= 9 && m >= 0 ? `0${m}` : m;
let hh = h <= 9 && h >= 0 ? `0${h}` : h;
return hh + ':' + mm + ':' + ss;
};
This may be the simple answer
var d1 = new Date(2014,10,11,1,43,28);
var d2 = new Date(2014,10,11,2,53,58);
var date = new Date(d2-d1);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
console.log(day + ":" + hour + ":" + min + ":" + sec)
More intuitive and easier to read.
function hmsToSeconds(t) {
const [hours, minutes, seconds] = t.split(':')
return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds)
}
function secondsToHMS(secs) {
return new Date(secs * 1000).toISOString().substr(11, 8)
}
var startTime = '01:43:28';
var endTime = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(endTime) - hmsToSeconds(startTime))); //10:39:18

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>

Running a Javascript Clock at 4x Speed [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript to run the Clock (date and time) 4 times speeder
I'm trying to make a clock that starts at a time value (hh:mm:ss) that I've supplied, and runs at 4x speed (for the server time of an online game that runs 4x actual time). I've modified a free clock that I found online to do this, but it only works for every other minute (try the code below to see exactly what I mean if that doesn't make sense).
var customClock = (function () {
var timeDiff;
var timeout;
function addZ(n) {
return (n < 10 ? '0' : '') + n;
}
function formatTime(d) {
t1 = d.getHours();
t2 = d.getMinutes();
t3 = d.getSeconds() * 4;
if (t3 > 59) {
t3 = t3 - 60;
t2 = t2 + 1;
}
if (t2 > 59) {
t2 = t2 - 60;
t1 = t1 + 1;
}
if (t1 > 23) {
t1 = 0;
}
return addZ(t1) + ':' + addZ(t2) + ':' + addZ(t3);
}
return function (s) {
var now = new Date();
var then;
var lag = 1015 - now.getMilliseconds();
if (s) {
s = s.split(':');
then = new Date(now);
then.setHours(+s[0], +s[1], +s[2], 0);
timeDiff = now - then;
}
now = new Date(now - timeDiff);
document.getElementById('clock').innerHTML = formatTime(now);
timeout = setTimeout(customClock, lag);
}
}());
window.onload = function () {
customClock('00:00:00');
};
Any idea why this is happening? I'm pretty new to Javascript and this is definitely a little hack-ey. Thanks
i take the orginal time and substract it from the current then multiply it by 4 and add it to the orginal time. I think that should take care or the sync problem.
(function(){
var startTime = new Date(1987,08,13).valueOf() //save the date 13. august 1987
, interval = setInterval(function() {
var diff = Date.now() - startTime
//multiply the diff by 4 and add to original time
var time = new Date(startTime + (diff*4))
console.log(time.toLocaleTimeString())
}, 1000)
}())
How to use with a custom date (use the Date object)
Date(year, month, day, hours, minutes, seconds, milliseconds)
var lag = 1015 - now.getMilliseconds(); is attempting to "run this again a smidge (15 ms) after the next clock tick". Make this value smaller (divide by 4?), and this code will run more frequently.
Next up, get it to show 4x the current clock duration. Similar problem: multiply now's details by 4 either inside or outside formatTime()
I would first create a Clock constructor as follows:
function Clock(id) {
var clock = this;
var timeout;
var time;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.stop = stop;
this.start = start;
var element = document.getElementById(id);
function stop() {
clearTimeout(timeout);
}
function start() {
timeout = setTimeout(tick, 0);
time = Date.now();
}
function tick() {
time += 1000;
timeout = setTimeout(tick, time - Date.now());
display();
update();
}
function display() {
var hours = clock.hours;
var minutes = clock.minutes;
var seconds = clock.seconds;
hours = hours < 10 ? "0" + hours : "" + hours;
minutes = minutes < 10 ? "0" + minutes : "" + minutes;
seconds = seconds < 10 ? "0" + seconds : "" + seconds;
element.innerHTML = hours + ":" + minutes + ":" + seconds;
}
function update() {
var seconds = clock.seconds += 4;
if (seconds === 60) {
clock.seconds = 0;
var minutes = ++clock.minutes;
if (minutes === 60) {
clock.minutes = 0;
var hours = ++clock.hours;
if (hours === 24) clock.hours = 0;
}
}
}
}
Then you can create a clock and start it like this:
var clock = new Clock("clock");
clock.start();
Here's a demo: http://jsfiddle.net/Nt5XN/

Categories