Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  110] [ 2]  / answers: 1 / hits: 198368  / 14 Years ago, wed, february 2, 2011, 12:00:00

Is there an alternative in JavaScript of getting time in milliseconds using the date object, or at least a way to reuse that object, without having to instantiate a new object every time I need to get this value? I am asking this because I am trying to make a simple game engine in JavaScript, and when calculating the delta frame time, I have to create a new Date object every frame. While I am not too worried about the performance implications of this, I am having some problems with the reliability of the exact time returned by this object.



I get some strange jumping in the animation, every second or so, and I am not sure if this is related to JavaScript's Garbage Collection or a limitation of the Date object when updating so fast. If I set the delta value to some constant, then the animation if perfectly smooth, so I am fairly sure this jumping is related to the way I get the time.



The only relevant code I can give is the way I calculate the delta time :



prevTime = curTime;
curTime = (new Date()).getTime();
deltaTime = curTime - prevTime;


When calculating movement / animation I multiply a constant value with the delta time.



If there is no way to avoid getting the time in milliseconds by using the Date object, would a function that increments a variable (being the elapsed time in milliseconds since the game started), and which is called using the SetTimer function at a rate of once every milliseconds be an efficient and reliable alternative?



Edit : I have tested now my code in different browsers and it seems that this jump is really only apparent in Chrome, not in Firefox. But it would still be nice if there were a method that worked in both browsers.


More From » javascript

 Answers
6

Try Date.now().



The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.


[#93936] Monday, January 31, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katelinb

Total Points: 535
Total Questions: 104
Total Answers: 109

Location: Burkina Faso
Member since Sun, Jun 13, 2021
3 Years ago
katelinb questions
;