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.
Related
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);
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>
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>
//i am checking if given time is lapsed or not compare to current machine time.
//i am not getting alert even time start time and endtime is lapsed.
var currDate = new Date();
var startDate = setTime("09:30:00");
var endDate = setTime("10:15:00");
// given an input string of format "hh:mm:ss", returns a date object with
// the same day as today, but the given time.
function setTime(timeStr) {
var dateObj = new Date(); // assuming date is today
var timeArr = timeStr.split(':'); // to access hour/minute/second
var hour = timeArr[0];
var minute = timeArr[1];
var second = timeArr[2];
dateObj.setHours(hour);
dateObj.setMinutes(minute);
dateObj.setSeconds(second);
return dateObj;
}
// now we can subtract them (subtracting two Date objects gives you their
// difference in milliseconds)
if (currDate - startDate < 0 || currDate - endDate < 0) {
alert("Unfortunately, you can't schedule a meeting in the past.
We apologize for the inconvenience.");
}
In order to check given time is lapsed or not compare to current machine time change the condition as mentioned below.
if (currDate > startDate && currDate < endDate)
{
alert("Unfortunately, you can't schedule a meeting in the past. We apologize for the inconvenience.");
}
It will show the alert if the current time falls in between start time and end time.
Let me know if it worked.
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' )