Alec Beyer
Alec Beyer

Reputation: 283

Nodejs getTime() only displays time of execution

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.

Upvotes: 1

Views: 61

Answers (1)

Ivan Vasiljevic
Ivan Vasiljevic

Reputation: 5718

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.

Upvotes: 1

Related Questions