Get current time from existing javascript Date () object?

I am writing real-time debug code in a javascript application. In the update loop I want:

  • get current time in milliseconds
  • compare last frame time and print frame rate
  • set the last frame time to the current time from the variable above

Everything is simple, except that since it is in such a performance-critical piece of code, I try not to call

var d=new Date(); 

every frame before i call

 thisFrameTime = d.getTime(); 

Is it possible? Is there something like:

 d.now 

which updates the time in an existing date object?

My thinking is that I want to stay away from memory allocation / gc in debug mode, so this affects the frame rate less - but maybe it's just not how it is done in javascript? (My background is more than C / C ++, so maybe this is the wrong way of thinking for JS?)

I searched google and qaru and can't find an answer that makes me think this is impossible. If this happens, confirmation will be helpful.

To love any thoughts - what is the most effective way to do this?

+4
source share
2 answers

There is a Date.now () function.

 var time = Date.now() 

The problem is that it is part of EcmaScript 5, so the older browser (IE 6-8) does not support it. As written in MDM (link above), you can solve this problem by including it in your code:

 if (!Date.now) { Date.now = function() { return +(new Date); }; } 
+4
source

You do not control gc in the browser, it starts when it starts. Creating Date objects every time you need the current time is probably the best way to do this and should be trivial if you do not keep references to objects (which will prevent them from being collected).

However, most likely you should use the AOP-style profiling code instead of throwing the "debug code" into your source. I don’t even know what it is, but it looks like something you should never do.

+1
source

Source: https://habr.com/ru/post/1384396/


All Articles