JAVASCRIPT - How update variable every second - javascript

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

Related

Check if time is falling under specific timeframe

I have a variable that stores a time value.
var cabtime = ["09:30:00"];
Variable time value is in 24-hour clock. That means 02:30:0PM will come as 14:30:00.
I want to check if the variable time falls under 08:00AM to 10:00AM window. If yes then I'll do an action.
Any pointers in this regard?
You could parse the time into seconds since midnight using:
var cabtime = ["HH:MM:SS"] // in 24hr time
function parseTime (string) {
parts = string.split(':').map(x => parseInt(x))
seconds = parts[0] * 3600 + parts[1] * 60 + parts[0]
return seconds
}
Then you can parse the time and the upper/lower bounds, and test using:
time = parseTime(cabtime[0])
lower = parseTime('08:00:00')
upper = parseTime('10:00:00')
if (time >= lower && time <= upper) {
print('Inside the range')
}
You can solve it easily by converting your strings to Date objects and compare them than.
var cabtime = ["09:30"];
function checkTimeRange(time, from, to, reldate) {
if (undefined === reldate) {
reldate = '0000T'; // the date the time strings are related to
}
let dtime = new Date(reldate + time);
let dfrom = new Date(reldate + from);
let dto = new Date(reldate + to);
return dfrom <= dtime && dtime <= dto;
}
checkTimeRange(cabtime[0], '08:00', '10:00'); // returns true
If you have full dates (e.g. '2019-07-25T09:30:00') instead of just the clock time you should provide for the parameter `reldate' an empty string.
* update: changed the wrong date format to standard format
* update: changed the date format again to be more fancy

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>

Filtering input by frequency (onoff debounce)

I'm using node on raspberry pi and module onoff to get input.
I want to only run function B if the function A is called twice in one minute
var gpio = require('onoff').Gpio;
var sensor = new gpio(7, 'in', 'falling');
var timeout = 60000;
var timeOfLastChange;
sensor.watch(function(err, value) {
console.log('Sensor value is now '+ value);
var currentTime = new Date(); //2 tick filter
if(value == false && timeOfLastChange < currentTime - timeout) var timeOfLastChange = new Date();
if(timeOfLastChange > currentTime - timeout) functionB();
});
gpio.setup(7, gpio.DIR_IN);
But this doesn't work.
if you change your date evaluations to milliseconds to match your timeout (int to int), then your date comparisons will work. something like this:
timeOfLastChange.getTime() > (currentTime.getTime() - timeout)
Or even better, don't use the date object, just the epoch millis like this:
currentTime = Date.now();
timeOfLastChange = Date.now();
Then your 'times' are an integer-like number, matching your timeout.

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