Running a Javascript Clock at 4x Speed [duplicate] - javascript

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/

Related

Updating the button element as a countdown timer through javascript

I want to create a countdown timer which looks like an fps counter for webpage...
after hours of time spent i m not able to find out what is wrong.....help
<script>
var myvar = setInterval(function () { startTimer() }, 1000);
function startTimer() {
var presentTime = 17 + ":" + 00;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if (s == 59) {
m = m - 1
}
//if(m<0){alert('timer completed')}
var button2 = document.createElement("Button2");
var interval = m + s;
button2.innerHTML = Math.round(interval);
button2.style = "top:0; left:0rem; height:10% ;color: black; background-color: #ffffff;position:fixed;padding:20px;font-size:large;font-weight: bold;";
setTimeout(startTimer, 1000);
document.body.appendChild(button2);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec
}; // add zero in front of numbers < 10
if (sec < 0) {
sec = "59"
};
return sec;
}
</script>
I can find three errors that hinder your code from performing correctly.
Multiple timers
First off since you invoke both a setInterval in outer scope, and then a setTimeout after each performed iteration, you will end up getting many unwanted timer instances that will do some crazy counting for you.
I recommend you to scrap either one of these and stick with just one of them.
For my example i happend to stick with the setInterval since you're executing the very same method over and over any way.
The initialization
Since the presentTime is declared inside the startTimer-function it will be constantly overwritten with 17 + ":" + 00 (resulting in "17:0" btw).
This is solved by declaring it in the outer scope instead.
Remembering the changes
Finally you need to save the current state of presentTime after modifications. Just adding a presentTime = [m,s].join(":"); at the end of startTimer() solves this.
var presentTime = "17:00";
function startTimer() {
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if (s == 59) {
m = m - 1
}
var button2 = document.createElement("Button2");
var interval = s;
button2.innerHTML = m + ":" + s;
button2.style = "top:0; left:0rem; height:10% ;color: black; background-color: #ffffff;position:fixed;padding:20px;font-size:large;font-weight: bold;";
document.body.appendChild(button2);
presentTime = [m,s].join(":");
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec
}; // add zero in front of numbers < 10
if (sec < 0) {
sec = "59"
};
return sec;
}
var interval = setInterval(startTimer, 1000);

Daily javascript countdown shorten to jquery

Found this daily countdown timer and edited it a little but I find it a little long and learned that Jquery is a shorter notation of javascript but don't know anything about it.
My knowledge is not advanced enough to either shorten this or change it to jquery.
I use the <body onload = "getSeconds()"> to start the daily countdown.
var reloadPage = false;
function getSeconds()
{
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var midnight = new Date(now.getFullYear(),now.getMonth(),now.getDate(),21,57,0); //midnight 0000 hrs
//midnight - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
var ft = midnight.getTime() + 86400000; // add one day 86 400 000
var diff = ft - time;
diff = parseInt(diff/1000);
if (diff > 86400) {diff = diff - 86400}
startTimer (diff);
}
var timeInSecs;
var ticker;
function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); //to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else
{
clearInterval(ticker); //stop counting at zero
if (secs == 0)
{
reloadPage = true;
console.log("reset");
};
getSeconds(); //and start again if required
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
if(reloadPage)
{
var result = "Please reload page for daily reset."
}
else
{
var result = ((hours <= 0 ) ? "" : hours + " hours ") + ( (mins <= 0) ? "" : mins + " minutes " ) + ( (mins <= 0) ? " < 1 minute " : "" );
}
document.getElementById("countdown").innerHTML = "Daily reset: " + result;
}
Here's your code "changed to jQuery"
var reloadPage = false;
function getSeconds()
{
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var midnight = new Date(now.getFullYear(),now.getMonth(),now.getDate(),21,57,0); //midnight 0000 hrs
//midnight - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
var ft = midnight.getTime() + 86400000; // add one day 86 400 000
var diff = ft - time;
diff = parseInt(diff/1000);
if (diff > 86400) {diff = diff - 86400}
startTimer (diff);
}
var timeInSecs;
var ticker;
function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); //to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else
{
clearInterval(ticker); //stop counting at zero
if (secs == 0)
{
reloadPage = true;
console.log("reset");
};
getSeconds(); //and start again if required
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
if(reloadPage)
{
var result = "Please reload page for daily reset."
}
else
{
var result = ((hours <= 0 ) ? "" : hours + " hours ") + ( (mins <= 0) ? "" : mins + " minutes " ) + ( (mins <= 0) ? " < 1 minute " : "" );
}
$("#countdown").html("Daily reset: " + result);
}
saving 27 bytes ... I'm sure loading 86000+ bytes of jQuery library wont negate this saving at all
a shorter implementation, imo. simpler, and no need for jQuery (even if you've already loaded it)
//a few values that come in handy when dealing with timestamps
MILLISECOND = MILLISECONDS = 1;
SECOND = SECONDS = 1000*MILLISECONDS;
MINUTE = MINUTES = 60*SECONDS;
HOUR = HOURS = 60*MINUTES;
DAY = DAYS = 24*HOURS;
TIMEZONE_OFFSET = new Date().getTimezoneOffset() * MINUTES;
var midnight = Date.now() + DAY - (Date.now() - TIMEZONE_OFFSET) % DAY;
function updateCountdown(){
//an utility to fetch the parts (hours, mins, ...) of the time
//and return a formated output
function fetch(factor, postfix){
var value = Math.floor(t/factor);
t %= factor; //beware: side-effect
//format the value
return value > 0?
value + (postfix == null? "": postfix):
"";
}
var t = midnight - Date.now(); //time till midnight
var countdown = document.querySelector("#countdown");
if(t <= 0){
countdown.innerHTML = "Please reload page for daily reset.";
location.reload();
}else{
countdown.innerHTML = [
"Daily reset:",
fetch(HOURS, " hours"),
fetch(MINUTES, " minutes"),
fetch(SECONDS, " seconds")
].join(" ");
setTimeout(updateCountdown, 200);
}
}
updateCountdown();
Edit:
how would I change the time to be resetted at
the variable midnight holds the target-timestamp I am counting to: t = midnight-Date.now()
change the target timestamp.
//a utility that gives you the timestamp for today `00:00 AM` (in your local timezone)
function today(){
var now = Date.now();
return now - (now - TIMEZONE_OFFSET) % DAY;
}
console.log( new Date( today() ) ); //today 00:00:00 GMT+yourTimeZoneOffset
define a target timezone:
var midnight = today() + 1*DAY;
var target = today() + 20*HOURS + 45*MINUTES + 59*SECONDS;
//you see how these constants get handy ;)
and compute the time to that target:
var t = target - Date.now();
the rest is the same

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.

Time remaining to the next 5 minutes - Javascript

I am trying to display the time remaining for the next 5 minutes (snapped to the full 5 minutes of the current time e.g., 15:05, 15:10..)
I was able to achieve the same for the time remaining for next Hour (Not minutes):
<span class="timer"></span>
<script>
function secondPassed() {
var cur_date = new Date();
var hour = cur_date.getHours();
var minutes = cur_date.getMinutes();
var seconds = cur_date.getSeconds();
var minutes_remain = parseInt(59 - parseInt(minutes));
var seconds_remain = parseInt(60 - parseInt(seconds));
var timers = document.getElementsByClassName('timer');
for (var i = 0; i < timers.length; i++) {
timers[i].innerHTML = minutes_remain+":"+seconds_remain;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
</script>
JSfiddle : http://jsfiddle.net/ov0oo5f7/
Something like this?
function secondPassed() {
var cur_date = new Date();
var minutes = cur_date.getMinutes();
var seconds = cur_date.getSeconds();
var timers = document.getElementsByClassName('timer');
for (var i = 0; i < timers.length; i++) {
timers[i].innerHTML = (4 - minutes % 5) + ":" + (seconds >= 50 ? "0" : "") + (59 - seconds);
}
}
var countdownTimer = setInterval(secondPassed, 1000);
<span class="timer"></span>
You can reduce the code a bit and to make it more accurate, use setTimeout and call the function as close as reasonable to the next full second. setInterval will slowly drift.
// Return the time to next 5 minutes as m:ss
function toNext5Min() {
// Get the current time
var secs = (new Date() / 1000 | 0) % 300;
// Function to add leading zero to single digit numbers
function z(n){return (n < 10? '0' : '') + n;}
// Return m:ss
return (5 - secs/60 | 0) + ':' + z(60 - (secs%60 || 60));
}
// Call the function just after the next full second
function runTimer() {
console.log(toNext5Min());
var now = new Date();
setTimeout(runTimer, 1020 - now % 1000);
}
The above ticks over on the full minute so that at say 10:00:00 it shows 5:00. If you'd rather is showed 0:00, then the last line of toNext5Min should be:
return (5 - (secs? secs/60 : 5) | 0) + ':' + z(60 - (secs%60 || 60));
This is what you need to change to get it to work the way you want:
var minutes = cur_date.getMinutes();
var seconds = cur_date.getSeconds();
try change it to this:
var minutes_remain = 5 - minutes%5 - 1;
var seconds_remain = 59 - seconds;
Try it out here: jsFiddle
Change your minutes remain to following line. It calculates current minute mod by 5 subtracted from 5, which is what you need.
function secondPassed() {
var cur_date = new Date();
var hour = cur_date.getHours();
var minutes = cur_date.getMinutes();
var seconds = cur_date.getSeconds();
var minutes_remain = parseInt(5 - parseInt(minutes%5));
var seconds_remain = parseInt(60 - parseInt(seconds));
var timers = document.getElementsByClassName('timer');
for (var i = 0; i < timers.length; i++) {
timers[i].innerHTML = minutes_remain+":"+seconds_remain;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
Updated fiddle http://jsfiddle.net/ov0oo5f7/2/
You can work out what the next 5 minutes interval will be if you divide by 5, round it up, and multiply by 5 again.
You need to handle if you are on an exact minute otherwise minutes_remain will show as 1 minute less.
In terms of being accurate, you don't need to parseInt everywhere as they are all numbers already. I've tried to make it as efficient as possible. In any case, you are only checking it once a second, so you can't guarantee accuracy.
http://jsfiddle.net/ov0oo5f7/6/
function secondPassed() {
var cur_date = new Date();
var hour = cur_date.getHours();
// handle 0 seconds - would be 60 otherwise
var seconds_remain = 60 - (cur_date.getSeconds() || 60);
// handle ceil on 0 seconds - otherwise out by a minute
var minutes = cur_date.getMinutes() + (seconds_remain == 0 ? 0 : 1);
var minutes_remain = Math.ceil(minutes/5) * 5 - minutes;
var timers = document.getElementsByClassName('timer');
for (var i = 0; i < timers.length; i++) {
timers[i].innerHTML = minutes_remain+":"+seconds_remain;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
If you are looking for the mechine time and counting it down for 5 minutes , then this might help -
var startTime = new Date();
function secondPassed() {
var cur_date = new Date();
if(parseInt((cur_date - startTime)/1000) >300 ){
window.clearInterval(countdownTimer);
}
var hour = cur_date.getHours();
var minutes = cur_date.getMinutes();
var seconds = cur_date.getSeconds();
var minutes_remain = parseInt(59 - parseInt(minutes));
var seconds_remain = parseInt(60 - parseInt(seconds));
var timers = document.getElementsByClassName('timer');
for (var i = 0; i < timers.length; i++) {
timers[i].innerHTML = minutes_remain+":"+seconds_remain;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
A simple approach is nothing that 5 minutes are 5*60*1000 milliseconds, thus
var k = 5*60*1000;
var next5 = new Date(Math.ceil((new Date).getTime()/k)*k);

Compute elapsed time [duplicate]

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

Categories