I am writing some debug code in a real-time javascript app. In the update loop, I want to:
- get current time in milliseconds
- compare to last frame’s time and print out framerate
- set last frame’s time to current time from the variable above
All straightforward, except that since it’s in such a performance-critical piece of code, I’m trying not to call
var d=new Date();
every frame before I call
thisFrameTime = d.getTime();
Is this possible? Is there something along the lines of:
d.now
which updates the time in the existing date object?
My thinking is that I want to stay away from memory allocation / gc while in debug mode so it impacts framerate less – but maybe that’s just not how it’s done in javascript? (My background is more C/C++, so maybe this is not the right way of thinking for JS?)
I have searched Google and Stack Overflow, and can’t seem to find an answer, which makes me think it’s not possible. If that’s the case, confirmation would be helpful.
Would love any thoughts – what’s the most performant way to get this done?
There is a Date.now() function.
The problem is that it is a part of EcmaScript 5 so older browser (IE 6-8) don’t support it. As written on the MDM (link above) you can solve this issue by including this into your code: