Continue a clicking clock when user chooses new time in JavaScript - 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>

Related

Add time stamp for hover in Leaflet map?

I'm using Leaflet to insert a map into Qualtrics. For one of my markers, I have it set up so that (1) a popup appears with a mouse hover and (2) clicking on the popup continues on to the next page in the experiment:
marker1.on('mouseover', function (e) {
this.openPopup();
this.getPopup()._contentNode.onclick = function () {
document.querySelector("#NextButton").click();
Qualtrics.SurveyEngine.setEmbeddedData("home", "one");
};
});
Is it also possible to use embedded data to also record when the mouse hover occurs with a time stamp? If so, how?
Use a function to get a new Date(). When no parameters are provided, the newly-created Date object represents the current date and time as of the time of instantiation. Then you can get the parameters you wish using the getDay(), getMonth(), getHours(), getMinutes(), etc... return your timestamp and then you can call on the function within your event listener mouseover.
Not sure how you wish to save it further however...
const getTimeStamp = () => {
let d = new Date();
let hours = d.getHours();
let meridian;
if (hours > 12) {
hours = hours - 12;
meridian = 'PM';
}else{
meridian = 'AM';
}
let time = `${hours}:${d.getMinutes()}:${d.getSeconds()} ${meridian}`;
let day = d.getDate();
let month = d.getMonth() + 1; // Since getMonth() returns month from 0-11 not 1-12
let year = d.getFullYear();
let timeStamp = `${month}/${day}/${year} - ${time}`;
return timeStamp;
}
let marker1 = document.getElementById('marker1')
marker1.addEventListener('mouseover', function(e) {
console.log(getTimeStamp())
// this.openPopup();
// this.getPopup()._contentNode.onclick = function() {
// document.querySelector("#NextButton").click();
// Qualtrics.SurveyEngine.setEmbeddedData("home", "one");
// };
});
<buttton id="marker1">Marker</div>

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

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>

check if "current time" is between 2 times. But also check for nights as the day before

I have 2 times for example: 10:00 and 1:00 now i want to check if current time... is between these 2 times in javascript.
The problem is that the closing time in this case is a next day so its before the openingstime. How can i do this the proper way for some reason i can not get around this.
i hav efound that this could solve it:
var start = new Date(2012,6,20,13).getTime();
var now = new Date().getTime();
var end = new Date(2012,6,21,2).getTime();
if( (start < now ) && (now < end )) {
console.log("opened");
}
else {
console.log("closed");
}
but how can i do it with 2 string formats like 10:00 and 2:00 because i do not see a option to put a time alone
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
You could use a simple function like this to convert your time to a number of minutes since 0:00:
function getMinutes(str) {
var time = str.split(':');
return time[0]*60+time[1]*1;
}
And a similar function to get the current time into the same form in order to compare:
function getMinutesNow() {
var timeNow = new Date();
return timeNow.getHours()*60+timeNow.getMinutes();
}
Then convert both opening and closing time and, if it happens that closing time is before opening time, add 24 hours to it.
var now = getMinutesNow();
var start = getMinutes('10:00');
var end = getMinutes('2:00');
if (start > end) end += getMinutes('24:00');
if ((now > start) && (now < end)) { // your code here
This is the solution I've gotten to after a bit of fiddling. At the current time of 3:24 am, it outputs the correct information. changing the now array to be [13,00] also gave the correct result of 'closed' Give it a test run through to make sure it works correctly.
Edit
jQuery included solely because I am brain dead.
Edit#2
I noticed now (9pm my time) that my conversion wasn't working, it was saying 'closed', when it shouldn't have. So far, this works for any and all numbers I've put in it to test.
var start_time = [20,00]
var end_time = [12,00]
//We've got the two start times as an array of hours/minutes values.
var dateObj = new Date(); //I just feel dirty making multiple calls to new Date().etc
var now = [dateObj.getHours(),dateObj.getMinutes()]; //Gets the current Hours/Minutes
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24; //This is something I came up with because I do a lot of math.
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
var el=$('#result');
var start_string = to_hms_string(start_time); //the start string converted to a string format. Made comparisons easier.
var end_string = to_hms_string(end_time); //See Above
var now_string = to_hms_string(now); //Above
console.log(start_string, now_string, end_string);
var status = (start_string < now_string && now_string < end_string) ? "Open" : "Closed";
el.html(status);
//Function to_hms_string stands for "hour-minute-second" string. First name that came up.
function to_hms_string(timearr){
var minutes = 60+timearr[1];
var hours = "";
if(Math.abs(timearr[0]) < 10){
hours = "0";
}
hours = (timearr[0]<0) ? "-"+hours+Math.abs(timearr[0]) : hours+timearr[0];
return hours+":"+minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
PlaceHolder
</div>
You can do this, get current time. Then define you start time and end time based on the current time getting the year, month, date for tomorrow's date add 1 to the start's date see code below. Then you can compare the time the same fi condition you have. Good luck
var now = new Date();
var start = new Date(now.getFullYear(),now.getMonth(),now.getDate(),7).getTime();
var end = new Date(now.getFullYear(),now.getMonth(),now.getDate() + 1,2).getTime();
now = now.getTime();
if( now >= start && now < end) {
console.log("opened");
}
else {
console.log("closed");
}
***EDIT**
You can convert the current time to millis after you get the year, month and date. Then use your current if condition.
Jhecht This thing right here:
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24;
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
it's brilliant. It works and this is the correct answer. Great job!

Time things with 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' )

Categories

Resources