Time things with Javascript - javascript

How can i time how much time passes between 2 events with javascript? like, to the millisecond?

When performing arithmetic operations on Date objects, they are implicitly converted to milliseconds (since 1970-01-01 00:00:00 UTC), so all you need to do is subtract a Date created when the operation started from a Date created when the operation ends.
var start = new Date();
doSomeHeavyWork();
var end = new Date();
var millisecondsElapsed = end - start;

Easiest way to do this.
console.time("timer name")
console.timeEnd("timer name")
This will output the time in milliseconds to the console.

It's surprisingly difficult to do.
var start = new Date();
// Do things here
var finish = new Date();
var difference = new Date();
difference.setTime(finish.getTime() - start.getTime());
alert( difference.getMilliseconds() );

Well, you can use firebug (firefox plugin) to benchmark your functions. Check this article : benchmark javascript funcions

What about making a reusable timer object?
Usage:
// event 1
document.getElementById('elId').onclick = function () {
timer.start('myTimer1');
};
// event 2
document.getElementById('otherElement').onclick = function () {
alert(timer.stop('myTimer1')); // alerts the time difference in ms
};
Implementation:
var timer = (function () {
var startTimes = {}; // multiple start times will be stored here
return {
start: function (id) {
id = id || 'default'; // set id = 'default' if no valid argument passed
startTimes[id] = +new Date; // store the current time using the timer id
},
stop: function (id) {
id = id || 'default';
var diff = (+new Date - startTimes[id]); // get the difference
delete startTimes[id]; // remove the stored start time
return diff || undefined; // return the difference in milliseconds
}
};
}());

var initialTime = (new Date).getTime(), i = 55000;
(function() {
while ( i-- ) {
setTimeout( function(){}, 20 );
}
})()
var finalTime = ( new Date ).getTime(), diff = (new Date);
diff.setTime( finalTime - initialTime );
alert( diff.getMilliseconds() + 'ms' )

Related

JAVASCRIPT - How update variable every second

I need to compare the start time with the current time, but I don't know how to make the current time always refresh to my variable that I compare.
I apologize for the edit, in the previous solution I wrongly described the error
var timeout = $payuEle.attr("data-ajax-timeout");
// VERIFICATION OF TIMEOUT TIME //
//////////////////////////////////
// Creates a new start date
var startTime = new Date();
// Converts the start date to milliseconds
var startTimeInMilliseconds = startTime.getTime();
// Converts seconds from the 'timeout' attribute to milliseconds
var secondsInMilliseconds = timeout * 1000;
// Adds milliseconds of start date + 'timeout' = time when authentication expires
var endTimeInMilliseconds = startTimeInMilliseconds + secondsInMilliseconds;
// Converts milliseconds of end time to date (functionally not redeemed, only for testing purposes in console)
var endTime = new Date(endTimeInMilliseconds);
// Predefined variable, which then saves the current time
var readyForActualTime = "";
// A variable calling a function for the current time
var actualTimeStore = getActualTime(readyForActualTime);
var actualTimeStoreInMilliseconds = actualTimeStore.getTime();
// Rounds the last two milliseconds to avoid minor variations
var endTimeCompare = Math.round(endTimeInMilliseconds/100)*100;
var startTimeCompare = Math.round(actualTimeStoreInMilliseconds/100)*100;
console.log(startTime, endTime);
// A function that creates the current time
function getActualTime(ocekavanyParametr) {
// Creates the current time
var actualTime = new Date();
// Returns current time to variable ''
return actualTime;
}
// It restores function every second to keep the actual time
setInterval(getActualTime, 1000);
// Compare times
if (endTimeCompare === startTimeCompare) {
alert('Its a match!');
}
Thank you for your help
You likely want this. You are vastly over complicating things and you need the creation of times inside the loop
var timeout = 5; // seconds
// VERIFICATION OF TIMEOUT TIME //
//////////////////////////////////
// Creates a new start date
var startTime = new Date();
startTime.setMilliseconds(0); // normalise
// Converts the start date to milliseconds
var startTimeInMilliseconds = startTime.getTime();
// Converts seconds from the 'timeout' attribute to milliseconds
var secondsInMilliseconds = timeout * 1000;
// Adds milliseconds of start date + 'timeout' = time when authentication expires
var endTimeInMilliseconds = startTimeInMilliseconds + secondsInMilliseconds;
// It restores function every second to keep the actual time
var tId = setInterval(getActualTime, 1000);
// A function that creates the current time
function getActualTime() {
// Creates the current time
var actualTime = new Date();
actualTime.setMilliseconds(0); // normalise
actualTimeInMilliseconds = actualTime.getTime();
console.log(new Date(endTimeInMilliseconds),new Date(actualTimeInMilliseconds));
// Compare times
if (endTimeInMilliseconds === actualTimeInMilliseconds) {
clearTimeout(tId)
console.log('Its a match!');
}
}
You only need to call the interval once because actualTime is inside the function. To see it more clearly, if you remove the variable and log new Date():
function logActualTime() {
console.log('Now is:', new Date());
}
setInterval(logActualTime, 1000);

How to get the time difference between two times in Javascript?

I have two times, say timeS = '00.00.00' and timeE = '10.00.00'
I want to get the time difference between the two times. One way is the following manner,
//create date format
var timeStart = new Date("01/01/2007 " + timeS).getHours();
var timeEnd = new Date("01/01/2007 " + timeE).getHours();
var hourDiff = timeEnd - timeStart;
Here, I had to get the desired result using the Date format. Is there any other way to achieve this, without explicitly making a Date object?
Note: Instead of marking it a duplicate, do observe that I am asking for some other alternative ways.
Convert the hh.mm.ss format into equivalent seconds by parsing.
var timeS = '00.00.00';
var timeE = '10.00.00';
function convertToSeconds(timeString) {
var timeSplit = timeString.split('.');
return timeSplit.reduce((result, item, index) => {
return result + Number(item) * Math.pow(60, timeSplit.length - index - 1)
}, 0);
}
const secondDifference = convertToSeconds(timeE) - convertToSeconds(timeS);
console.log(secondDifference);
You need to convert this time to a Date first
var convertToMS = time => {
var d = new Date(1,1,1);
d.setHours.apply( d, time.split(".").map( Number ) );
return d.getTime();
};
var diffOutput = convertToMS( timeE ) - convertToMS( timeS );
Demo
var convertToMS = time => {
var d = new Date();
d.setHours.apply(d, time.split(".").map(Number));
return d.getTime();
};
var timeS = '00.00.00';
var timeE = '10.00.00';
var diffOutput = convertToMS(timeE) - convertToMS(timeS);
console.log(diffOutput)
Edit
As suggested by #RobG, check this alternate solution using UTC
var convertToMS = time => Date.UTC(1,1,1, ...time.split('.'));

How to compare opening hours?

I want to compare opening hours stored on my server with the current time.
Given the following:
start: 09.00
end: 00.30
I want the result if the store is open or closed. When the current time isn't in the given start and end time the store is closed.
The code i use until now does not work. I get the error:
TypeError: Cannot read property '3' of undefined
firebase.database().ref("v3/standalonelist/bars").on('value', function(snapshot) {
$timeout(function() {
$scope.content = snapshot.val();
snapshot.forEach(function(childSnapshot) {
$scope.data1 = [childSnapshot.val()];
$scope.locations1 = $scope.data1
$scope.locations1.forEach(function(item) {
$scope.getMinutes = function(str) {
var time = str.split('.');
return time[0] * 60 + time[1] * 1;
}
$scope.getMinutesNow = function() {
var timeNow = new Date();
return timeNow.getHours() * 60 + timeNow.getMinutes();
}
var a = new Date();
var day = a.getDay(); // 3
var now = $scope.getMinutesNow();
console.log(item.opens[day]); // returns 09.00
var start = $scope.getMinutes(item.opens[day]); // 09.00
var end = $scope.getMinutes(item.closes[day]); // 01.20
if (start > end) {
end += $scope.getMinutes('24.00');
}
if ((now > start) && (now < end)) {
$scope.$apply(function() {
$scope.open = true; // Store is open
})
} else {
$scope.open = false; // Store is closed
}
})
})
I think you are making it a little more complicated than it has to be...
var today = new Date(),
open = "Open",
closed = "Closed",
display = document.getElementById('display'),
start = new Date(), end = new Date();
// Set the opening hour:minutes
start.setHours(10);
start.setMinutes(5);
// Set the closing hour:minutes
end.setHours(18);
end.setMinutes(30);
// Check the time based on milliseconds
if (
today.getTime() >= start.getTime() &&
today.getTime() < end.getTime()
) {
display.innerHTML = open;
} else {
display.innerHTML = closed;
}
Here is a working fiddle: http://jsfiddle.net/L770r2qk/
You might also want to take into account different days, such as a business that runs from late night to early morning. For that you would also want to use start.setDate(12) and end.setDate(13). You then might also want to take into account month changes where you would then use start.setMonth(10) and end.setMonth(11).
Those extra features are up to you and I will let you implement them into the example.

Continue a clicking clock when user chooses new time in JavaScript

I've run into a problem whilst building a clock using Vanilla Javascript.
I'm getting the current time fine but I would like the user to be able to set their own time. The time the user wants is grabbed from three input fields and passed in as optional paramters(updateH,updateM,updateS) to the below function:
function updateTime(updateH,updateM,updateS){
updateH = updateH || false; updateM = updateM || false; updateS = updateS || false;
today = new Date();
if (updateH != false || updateM != false || updateS != false) {
today.setHours(updateH);
today.setMinutes(updateM);
today.setSeconds(updateS);
}
h = addLeadingZeroes(today.getHours()); //Today's time (hours)
m = addLeadingZeroes(today.getMinutes()); //Today's time (minutes)
s = addLeadingZeroes(today.getSeconds()); //Today's time (seconds)
day = getDay().toUpperCase(); //Today's date (day)
date = today.getaDmante(); //Today's date (date)
month = getMonth().toUpperCase(); //Today's date (month)
time24H = h + ":" + m + ":" + s;
drawWatch();
setTimeout(updateTime, 1000);
}
updateTime();
This function is ran every second (1000ms), therefore the clock resets itself to the current time after one second, making the users choice time dissapear.
Is there anyway to update the time to the user passed in time and then continue the clock ticking using the new time? E.G:
The clock reads '12:00:00', the user then enters the time '13:30:00', now the clock continues ticking from '13:30:01....13:30:02....13:30:03...ETC'.
Many thanks for your help!
When the user sets the their time, calculate the difference between their time and the current time, store this value. Then each time you want to redraw the watch just get the new current time, subtract that stored difference and redraw the watch.
Personally I would create a new prototype called "Watch" and just do all the things you want within this object.
/* Create a "Watch" prototype */
function Watch(hours, minutes, seconds, drawInterval){
var t = this;
this.offset = 0;
this.drawInterval = drawInterval || 1000;
this.setTime = function(hours, minutes, seconds){
var now = new Date().getTime();
var theirTime = new Date();
if(hours) theirTime.setHours(hours);
if(minutes) theirTime.setMinutes(minutes);
if(seconds) theirTime.setSeconds(seconds);
this.offset = now - theirTime.getTime();
};
this.getTime = function(){
var d = new Date( new Date() - this.offset );
return d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
};
this.draw = function(elementID){
function draw(){
document.getElementById(elementID).innerHTML = t.getTime();
setTimeout(draw, t.drawInterval);
};
draw();
};
this.setTime(hours, minutes, seconds); // Initialize
}
/* Create an instance of the "Watch" prototype */
var W = new Watch();
/* Draw the watch to the DOM */
W.draw("watch");
/* Set the Users Time */
W.setTime(12,45,30); // 12:45:30
<div id='watch'></div>

Javascript's date object toLocaleTimeString adds an hour

I'm trying to create a timer from when the user clicks a button.
To do this I tried to calculate the difference between two date objects. When I output the difference, it works. However thetoLocaleTimeString call returns a string with an extra hour added:
var start;
var timer;
function myTimer() {
var current = new Date();
var difference = new Date(current - start);
console.log(difference.getTime(), difference.toLocaleTimeString(navigator.language));
document.getElementById("timer").innerHTML = difference;
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString('en-GB');
}
start = new Date();
timer = setInterval(myTimer, 1000);
draw();
<h1 id="timer"></h1>
<h1 id="timer2"></h1>
What am I doing wrong?
Specify the time zone as UTC in the options argument. Otherwise, the difference date will be adjusted to the user agent's time zone.
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString('en-GB', { timeZone: 'UTC' });
Read more on the options argument and toLocaleTimeString in the MDN documentation.
var start;
var timer;
function myTimer() {
var current = new Date();
var difference = new Date(current - start);
console.log(difference.getTime(), difference.toLocaleTimeString(navigator.language));
document.getElementById("timer").innerHTML = difference;
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString(navigator.language, { timeZone: 'UTC', hour12: false });
}
start = new Date();
timer = setInterval(myTimer, 1000);
draw();
<h1 id="timer"></h1>
<h1 id="timer2"></h1>
Because of the problems with JS and timezones, you are better of using something like moment.js's timezone (http://momentjs.com/timezone/) to do correct conversions (that keep in mind the shift of BST, GMT, differences between countries, etc..). For the purpose of your timer, the following would work as well, and is more accurate as well as simpler to reason about:
// Use Date.now() to get the time in milliseconds for this local computer
var start = Date.now();
var time = new Date();
// This function will prepend a 0 to a number lower than 10
function prependZero(v){
if(v < 9) return '0' + v;
else return v;
}
var timer = setInterval(function() {
// Calculate the difference using the computers local time strings
var difference = new Date(Date.now() - start);
document.getElementById("timer").innerHTML = new Date();
// Now use the Date mnethods to get the correct output:
document.getElementById("timer2").innerHTML = prependZero(difference.getHours()) + ':' + prependZero(difference.getMinutes()) + ':' + prependZero(difference.getSeconds());
}, 1000);
<h1 id="timer"></h1>
<h1 id="timer2"></h1>

Categories

Resources