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?
編集: コードをさまざまなブラウザでテストしたところ、この「ジャンプ」は実際には Chrome でのみ発生し、Firefox では発生しないようです。しかし、両方のブラウザで機能する方法があればなお良いでしょう。
ベストアンサー1
試す日付.now()。
スキップは、おそらくガベージ コレクションが原因です。通常、ガベージ コレクションは、変数をできるだけ再利用することで回避できますが、ガベージ コレクションの一時停止を減らすためにどのような方法を使用できるかを具体的に言うことはできません。