Nodejs getTime() only displays time of execution - javascript

I am working in a Nodejs application that is constantly running and I need to get the current system time every second. The problem is that is only displays the same time repeatedly rather than following the system time.
var date = new Date();
setInterval(function(){
console.log(date.getTime());
}, 1000);
This will just keep returning the exact same timestamp every second when I need it to return what the current system time is, in real time.

Well you should create new Date when function is executed. So this should work:
setInterval(function(){
var date = new Date();
console.log(date.getTime());
}, 1000);
What is the difference?
Well you created your date before execution of setInterval function. When function is executed you are getting time when object is created. In your example that is before calling setInterval function. In my example, date object is created every time when interval expire and function is called.
I hope that I have helped you.

Related

setInterval not working with content auto update

I'm trying to use this https://codepen.io/zeinab92/pen/xwWGWM
But It's not updating 'Hours, Minutes and Status' automatically without page reload.
How can I make it working so, times will automatically update and state text will also update based on the time condition whether it's Open or Closed.
I like the script except the auto update problem, I tried by create a new function,
setInterval(function() {
$("#timeDiv").html(data);
}, 1000);
by disabling default
setInterval(checkTime, 1000);
or setTimeout instead of setInterval
But no luck.
After debugging, I found the problem with the code.
You have declared now as global variable outside checkTime function and when page loads now variable stores value of new Date i.e the value of Date when page has been loaded. Hence the value of now is updated only once as global variable are executed only once.
Solution: Place the now variable inside checkTime so that each time it will have new value of Date whenever checkTime is called.
function checkTime(){
var now=new Date();
....
}
Hope this resolves the issue. (JS Fiddle)

Efficient way to run code based on time

I want to run come specific code after specific timing but with a efficient technique, Not with SetTimeout/SetInterval.
Like request to Database to check data on a after specific time dialy.
I want to query database at after 5:00 pm. So i write this code.
function checkVotingQuestionTime{
var currentDate = new Date();
if(currentDate .getHours =>5){
//go to database
}
}
But I have to write this code in setInterval(checkVotingQuestionTime, 60000);
Is there any better way to do this job? I guess current code is performance killer. register event etc
I would recommend using a 3rd party solution like
http://bunkat.github.io/later/
or
http://bunkat.github.io/schedule/
The first will overwrite setInterval() for you, so that you can use later schedules instead of providing a timeoffset in milliseconds:
https://bunkat.github.io/later/execute.html#set-interval

Get correct epoch time from client even if time on client is wrong

I am building a real time web app that requires epoch time from client. The calculation is involving a timestamp coming from my server and the timestamp from the client. I use the following code to get the epoch timestamp from client using JS:
var milliseconds = Math.floor((new Date).getTime()/1000);
JS is client based, so the value retrieved is based on the date/time the client has. So there is a possibility that the client date/time is misconfigured and the epoch time retrieved is wrong.
Is there a way to make sure that the epoch time from client is the correct one? Or is there a way to correct it if wrong?
Sure, i can use AJAX to get the epoch time from server, but since i use that time inside a countdown function, this means i have to hit the server every second..
[The reason i don't add a second to current time in every loop, is because i have problem when a mobile device sleeps. When the mobile device wakes up it starts counting down from where it were when turned off. It will not consider that the current time is increased. ]
Any advice would be appreciated!
var getClientMillis = function() {
return Date.now();
}
var realStartTime = getServerMillis();
var clientStartTime = getClientMillis();
var getCurrentMillis = function() {
return realStartTime + (getClientMillis() - clientStartTime);
}
You need to implement getServerMillis() yourself.

updating a Date object on the client side after getting the correct Date from the server side

I have a UI that needs to have the UTC time updated all the time to be shown to the users.
my original code was this:
(function () {
$http.get('api/getdate').success(function (data) {
current = new Date(data.res + new Date().getTimezoneOffset()*60*1000);
updateDateTimer = setInterval(function(){
$http.get('api/getdate').success(function (data) {
current = new Date(data.res + new Date().getTimezoneOffset()*60*1000);
});
}, 30000);
});
})();
data.res has the correct timestamp i need. this way works fine because i can trust my server with the data that is sent back to the UI. then the only data that i need from the user is its offset from UTC and thus i am sure the date that will be displayed will be correct.
my problem is that a call to the server will be made every 30 seconds, and if i want my clock to change even more often then this can get really nasty.
i thought about making the call to the server only one time and then add 1 second with a timer to the Date object created but this is very not accurate and after a few minutes you can see that the clock is not synchronized any more with the real time.
is there any possibly to not make more calls to the server after the first time?
the problem is that i can't make sure the client won't change its local clock. it seems i need to some how deal with the Date object that is being created with the first .get call, but how?
thanks
Could you please clarify the question a bit? If the only thing you're trying to do is find/show the current UTC time, new Date().getTime() returns the millis since January 1, 1970 UTC so that time is already in UTC (2 calls of getTime() occurring simultaneously in New York and Los Angeles will show the same number). Then you have some UTC functions on the Date object which give you the UTC time, like getUTCHours(), getUTCMinutes and getUTCSeconds().

Javascript setTimer

I'm having a hard time understanding the logic behind the setTimer method in javascript.
<html><head>
<script>
function Timer () {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
document.getElementById('show').innerHTML=h+":"+m+":"+s;
t = setTimeout("Timer()", 1000);
}
</script>
</head>
<body onload="Timer()">
<div id="show"></div>
</body></html>
setTimeout is used to delay a function/method execution. Then why it is being used in a real-time clock?
t = setTimeout("Timer()", 1000);
This part is confusing.
The clock is recursively calling itself, after the elapsed period of time.
Making a real-time clock is impossible in JS.
Because of how JS engines work, if you put Timer in a loop, to run for an infinite period of time, you'd never see the time update on the screen (as changes aren't drawn to the window until a function finishes and there's a gap in the program).
Also, inside that infinite-loop, it would be impossible to do anything else with the page (even closing it), because JS can only do one thing at a time, so it can't listen to any of the user's clicking until it's done with this loop.......
So that's what the setTimeout is for.
Timer is the function which acts as the clock.
Inside of the Timer function, at the end when all of the work is done, it's telling setTimeout to wait 1 second (1000ms) and then to call a function called Timer.
Timer just so happens to be the same function. But setTimeout doesn't know that, and doesn't care.
The t in this case is largely useless. setTimeout will return a number -- like taking a number at the doctor's office.
If, before you go through with it, you decide to back out, you can call clearTimeout(t); and it'll skip over that call (in this case, it would stop calling the clock).
There are a few bad-practices in here, that I figure I should mention, so that you can try not to copy them in your own practice.
First:
Pass setTimeout a reference to a function, and not a string...
var runThisFunction = function () { console.log("It's the future!"); },
time_to_wait = 250;
// DON'T DO THIS
setTimeout( "runThisFunction()", 250 );
// DO THIS
setTimeout( runThisFunction, 250 );
The difference is that setTimeout will run that string through eval, which can be a huge security concern depending on what you're trying to do.
The second problem is setting a random global variable, t... ...and hoping to use that as a solution.
First, in a couple of years, JS engines are going to start yelling at people for doing that stuff. Second, it's a huge hole, because any part of any app on that page could then overwrite t, or you could be relying on t somewhere else in your script, but every 1000ms, it gets written over with a new number.
Instead, they probably should have used a Timer.start(); and Timer.stop(); setup.
Your code:
t = setTimeout("Timer()", 1000);
The first thing you should know is that it's considered bad practice to put the first parameter in a string -- it should be the function name, unquoted, and without brackets, like so:
t = setTimeout(Timer, 1000);
That aside, your question about why it's being used to display a clock:
The use of setTimeout() inside the Timer() function to call itself is a common Javascript pattern to get a function to be called repeatedly. setTimeout() itself only triggers the function to be called a single time, after the given period of time has elapsed, so for a repeating event it needs to be re-triggered every time.
Since the setTimeout call is inside the Timer() function, it won't be set until Timer() is called the first time by some other means. This is where the body onload comes in.
As you suspect, setTimeout() isn't an accurate method for guaranteeing that a function will be called after exactly a given amount of time. Javascript is not multi-threaded, so any event handlers that are triggered must wait for any other code that is running at the same time. If something else is running slowly, this may cause your timer not to be triggered at exactly the moment it wants to be.
However, this isn't really a problem for your clock , because the clock is setting itself to the actual system time rather than relying on the setTimeout loop to keep itself in sync; the setTimeout loop is simply being used to make sure the display is updated (approximately) once a second. If it isn't actually quite exactly once a second, it doesn't really matter.
I hope that helps explain things a bit better.
When the Timer() function is called, it schedules itself to be run again one second later. The end result is once every second, Timer() updates the show element with the current time. (I have no idea why it's assigned to t, unless t is used in some other code on the page.)
The line starts The function again after one second.

Categories

Resources