Compute elapsed time [duplicate] - javascript

This question already has answers here:
How to measure time taken by a function to execute
(30 answers)
Closed 9 years ago.
I am looking for some JavaScript simple samples to compute elapsed time. My scenario is, for a specific point of execution in JavaScript code, I want to record a start time. And at another specific point of execution in JavaScript code, I want to record an end time.
Then, I want to calculate the elapsed time in the form of: how many Days, Hours, Minutes and Seconds are elapsed between end time and start time, for example: 0 Days, 2 Hours, 3 Minutes and 10 Seconds are elapsed.
Any reference simple samples? :-)
Thanks in advance,
George

Try something like this (FIDDLE)
// record start time
var startTime = new Date();
...
// later record end time
var endTime = new Date();
// time difference in ms
var timeDiff = endTime - startTime;
// strip the ms
timeDiff /= 1000;
// get seconds (Original had 'round' which incorrectly counts 0:28, 0:29, 1:30 ... 1:59, 1:0)
var seconds = Math.round(timeDiff % 60);
// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);
// get minutes
var minutes = Math.round(timeDiff % 60);
// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);
// get hours
var hours = Math.round(timeDiff % 24);
// remove hours from the date
timeDiff = Math.floor(timeDiff / 24);
// the rest of timeDiff is number of days
var days = timeDiff ;

Try this...
function Test()
{
var s1 = new StopWatch();
s1.Start();
// Do something.
s1.Stop();
alert( s1.ElapsedMilliseconds );
}
// Create a stopwatch "class."
StopWatch = function()
{
this.StartMilliseconds = 0;
this.ElapsedMilliseconds = 0;
}
StopWatch.prototype.Start = function()
{
this.StartMilliseconds = new Date().getTime();
}
StopWatch.prototype.Stop = function()
{
this.ElapsedMilliseconds = new Date().getTime() - this.StartMilliseconds;
}

Hope this will help:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>compute elapsed time in JavaScript</title>
<script type="text/javascript">
function display_c (start) {
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh = 1000; // Refresh rate in milli seconds
if( window.start >= end ) {
mytime = setTimeout( 'display_ct()',refresh )
} else {
alert("Time Over ");
}
}
function display_ct () {
// Calculate the number of days left
var days = Math.floor(window.start / 86400);
// After deducting the days calculate the number of hours left
var hours = Math.floor((window.start - (days * 86400 ))/3600)
// After days and hours , how many minutes are left
var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
// Finally how many seconds left after removing days, hours and minutes.
var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))
var x = window.start + "(" + days + " Days " + hours + " Hours " + minutes + " Minutes and " + secs + " Secondes " + ")";
document.getElementById('ct').innerHTML = x;
window.start = window.start - 1;
tt = display_c(window.start);
}
function stop() {
clearTimeout(mytime);
}
</script>
</head>
<body>
<input type="button" value="Start Timer" onclick="display_c(86501);"/> | <input type="button" value="End Timer" onclick="stop();"/>
<span id='ct' style="background-color: #FFFF00"></span>
</body>
</html>

Something like a "Stopwatch" object comes to my mind:
Usage:
var st = new Stopwatch();
st.start(); //Start the stopwatch
// As a test, I use the setTimeout function to delay st.stop();
setTimeout(function (){
st.stop(); // Stop it 5 seconds later...
alert(st.getSeconds());
}, 5000);
Implementation:
function Stopwatch(){
var startTime, endTime, instance = this;
this.start = function (){
startTime = new Date();
};
this.stop = function (){
endTime = new Date();
}
this.clear = function (){
startTime = null;
endTime = null;
}
this.getSeconds = function(){
if (!endTime){
return 0;
}
return Math.round((endTime.getTime() - startTime.getTime()) / 1000);
}
this.getMinutes = function(){
return instance.getSeconds() / 60;
}
this.getHours = function(){
return instance.getSeconds() / 60 / 60;
}
this.getDays = function(){
return instance.getHours() / 24;
}
}

var StopWatch = function (performance) {
this.startTime = 0;
this.stopTime = 0;
this.running = false;
this.performance = performance === false ? false : !!window.performance;
};
StopWatch.prototype.currentTime = function () {
return this.performance ? window.performance.now() : new Date().getTime();
};
StopWatch.prototype.start = function () {
this.startTime = this.currentTime();
this.running = true;
};
StopWatch.prototype.stop = function () {
this.stopTime = this.currentTime();
this.running = false;
};
StopWatch.prototype.getElapsedMilliseconds = function () {
if (this.running) {
this.stopTime = this.currentTime();
}
return this.stopTime - this.startTime;
};
StopWatch.prototype.getElapsedSeconds = function () {
return this.getElapsedMilliseconds() / 1000;
};
StopWatch.prototype.printElapsed = function (name) {
var currentName = name || 'Elapsed:';
console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};
Benchmark
var stopwatch = new StopWatch();
stopwatch.start();
for (var index = 0; index < 100; index++) {
stopwatch.printElapsed('Instance[' + index + ']');
}
stopwatch.stop();
stopwatch.printElapsed();
Output
Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]
performance.now() is optional - just pass false into StopWatch constructor function.

This is what I am using:
Milliseconds to a pretty format time string:
function ms2Time(ms) {
var secs = ms / 1000;
ms = Math.floor(ms % 1000);
var minutes = secs / 60;
secs = Math.floor(secs % 60);
var hours = minutes / 60;
minutes = Math.floor(minutes % 60);
hours = Math.floor(hours % 24);
return hours + ":" + minutes + ":" + secs + "." + ms;
}

First, you can always grab the current time by
var currentTime = new Date();
Then you could check out this "pretty date" example at http://www.zachleat.com/Lib/jquery/humane.js
If that doesn't work for you, just google "javascript pretty date" and you'll find dozens of example scripts.
Good luck.

<script type="text/javascript">
<!-- Gracefully hide from old browsers
// Javascript to compute elapsed time between "Start" and "Finish" button clicks
function timestamp_class(this_current_time, this_start_time, this_end_time, this_time_difference) {
this.this_current_time = this_current_time;
this.this_start_time = this_start_time;
this.this_end_time = this_end_time;
this.this_time_difference = this_time_difference;
this.GetCurrentTime = GetCurrentTime;
this.StartTiming = StartTiming;
this.EndTiming = EndTiming;
}
//Get current time from date timestamp
function GetCurrentTime() {
var my_current_timestamp;
my_current_timestamp = new Date(); //stamp current date & time
return my_current_timestamp.getTime();
}
//Stamp current time as start time and reset display textbox
function StartTiming() {
this.this_start_time = GetCurrentTime(); //stamp current time
document.TimeDisplayForm.TimeDisplayBox.value = 0; //init textbox display to zero
}
//Stamp current time as stop time, compute elapsed time difference and display in textbox
function EndTiming() {
this.this_end_time = GetCurrentTime(); //stamp current time
this.this_time_difference = (this.this_end_time - this.this_start_time) / 1000; //compute elapsed time
document.TimeDisplayForm.TimeDisplayBox.value = this.this_time_difference; //set elapsed time in display box
}
var time_object = new timestamp_class(0, 0, 0, 0); //create new time object and initialize it
//-->
</script>
<form>
<input type="button" value="Start" onClick="time_object.StartTiming()"; name="StartButton">
</form>
<form>
<input type="button" value="Finish" onClick="time_object.EndTiming()"; name="EndButton">
</form>
<form name="TimeDisplayForm">
Elapsed time:
<input type="text" name="TimeDisplayBox" size="6">
seconds
</form>

write java program that enter elapsed time in seconds for any cycling event & the output format should be like (hour : minute : seconds ) for EX : elapsed time in 4150 seconds= 1:09:10

Related

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

Issue on Updating jQuery Timeout

I am trying to make a simple plugin to calculate date and time by this code:
<div id="timer"></div>
<script>
$.fn.timeCounter = function(time) {
var target = new Date(time);
var now = new Date();
var timeDiff = target.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#timer").append( "<p>"+days+"</p>" );
$("#timer").append( "<p>"+hours+"</p>" );
$("#timer").append( "<p>"+minutes+"</p>" );
$("#timer").append( "<p>"+seconds+"</p>" );
var timer = setTimeout('timeCounter',1000);
};
$("#timer").timeCounter("june 16, 2014 00:01:00");
</script>
the code is working fine but I am having problem on displaying actual count down on numbers! can you please let me know how to fix this?
Thanks
Following displays count down in seconds:
$.fn.timeCounter = function(time) {
var target = new Date(time);
var now = new Date();
var timeDiff = target.getTime() - now.getTime();
// count down logic
setTimeout(function cdtd(){
if (timeDiff > 0){
// reduce one seconds
timeDiff-=1000;
// change this to a more dedicated display per your requirements
$('#timer').html(timeDiff/1000);
// next one second, reference to cdtd
setTimeout(cdtd,1000);}
},1000);
}
See working sample:
http://jsfiddle.net/danyu/X33kv/

Javascript timer just for minutes and seconds

I found a JSFiddle with a timer that counts up every second.
Except i want this to work with just the minutes and seconds. No hours.
Any ideas?
DATE_OBJ.getSeconds() to get seconds of Date object.
DATE_OBJ. getMinutes() to get minutes of Date object.
setInterval to invoke handler function after every second(1000ms).
var handler = function() {
var date = new Date();
var sec = date.getSeconds();
var min = date.getMinutes();
document.getElementById("time").textContent = (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec);
};
setInterval(handler, 1000);
handler();
<h1 id="time" style="text-align: center"></h1>
Here's a very hackish approach - http://jsfiddle.net/gPrwW/1/
HTML -
<div id="worked">31:14</div>
JS :
$(document).ready(function (e) {
var $worked = $("#worked");
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() + 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1]+":"+ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
The precise way of handling this is the following:
store the time of the start of the script
in a function that gets called repeatedly get the time elapsed
convert the elapsed time in whatever format you want and show it
Sample code:
var initialTime = Date.now();
function checkTime(){
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
document.getElementById('time').innerHTML = '' + formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return minutes + ':' + seconds;
}
window.setInterval(checkTime, 100);
You can easily change the granularity of checking the time (currently set at 0.1 seconds). This timer has the advantage that it will never be out of sync when it updates.
You can make a function that increments a counter every time it's called, shows the value as:
counter/60 minutes, counter%60 seconds
Then you can use the setInterval function to make JavaScript call your code every second. It's not extremely precise, but it's good enough for simple timers.
var initialTime = Date.now();
function checkTime(){
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
document.getElementById('time').innerHTML = '' + formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return minutes + ':' + seconds;
}
window.setInterval(checkTime, 100);
This might be something?
plain count up timer in javascript
It is based on the setInterval method
setInterval(setTime, 1000);

How to convert JavaScript functions to jQuery for a countdown timer on load of a page

I have the following code for a countdown timer. I need to convert the JavaScript portion to jQuery. The countdown timer starts on page load. How can I do that, as I have to load the diffTime function on load of the page. Please help me. Thanks in advance.
Edit: I got that the jquery call can not access ** function Tick() ** from ** function CreateTimer() ** . Is there any library for ** setTimeout() ** in jQuery? As I know so far, it is native to JS.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
//UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
//alert("Time's up!")
document.getElementById("timeMsg").innerHTML = "Market closed!! ";
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : + Time;
}
function diffTime(){
var startTime = 10*60 + 30; //starting time in minute
var lastTime = 16*60 + 30; //ending time in minutes
var thisTime = new Date(); // now
var currentYear = thisTime.getFullYear();
var currentMonth = thisTime.getMonth();
var currentDay = thisTime.getUTCDate();
var currentHour = thisTime.getHours();
var currentMinute = thisTime.getMinutes();
var currentTime = currentHour*60 + currentMinute; //current time in minute
if(currentTime >= startTime && currentTime < lastTime){
var endTime = new Date(currentYear,currentMonth,currentDay,16,30); // 4:30pm
var diff = endTime.getTime() - thisTime.getTime(); // now
var remainTime = diff / (1000); // positive number of days
remainTime = Math.ceil(remainTime);
CreateTimer("timer", remainTime);
}else{
document.getElementById("timeMsg").innerHTML = "Market closed!! ";
document.getElementById("timer").innerHTML = "00:00:00";
}
}
window.onload = diffTime;
</script>
</head>
<body>
<div><span id="timeMsg">Elapsed time remain: </span><b><span id='timer'></span></b></div>
</body>
Call the function in document.ready()
$( document ).ready( function ()
{
diffTime();
});
If you want it to start after the entire (ie. images, objects, etc.) page has loaded:
$(window).load(function() {}
Otherwise you can start the timer when the HTML has been loaded & DOM is ready:
$(document).ready(function() {}

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