在 javascript 中以毫秒为单位获取时间的更好方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4874408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:33:19  来源:igfitidea点击:

Better way of getting time in milliseconds in javascript?

javascript

提问by Colin Dumitru

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.

JavaScript 中是否有使用日期对象以毫秒为单位获取时间的替代方法,或者至少有一种方法可以重用该对象,而不必在每次需要获取此值时实例化一个新对象?我问这个是因为我试图用 JavaScript 制作一个简单的游戏引擎,并且在计算“增量帧时间”时,我必须每帧创建一个新的 Date 对象。虽然我不太担心这对性能的影响,但我在此对象返回的确切时间的可靠性方面遇到了一些问题。

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.

我每隔一秒左右就会在动画中出现一些奇怪的“跳跃”,我不确定这是否与 JavaScript 的垃圾收集或更新如此快时 Date 对象的限制有关。如果我将 delta 值设置为某个常量,那么动画就会非常平滑,所以我很确定这种“跳跃”与我获取时间的方式有关。

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?

如果无法避免使用 Date 对象获得以毫秒为单位的时间,那么会增加一个变量的函数(即自游戏开始以来经过的时间以毫秒为单位),并使用 SetTimer 函数以每毫秒一次是一种高效可靠的替代方案吗?

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.

编辑:我现在已经在不同的浏览器中测试了我的代码,似乎这种“跳转”实际上只在 Chrome 中明显,而不是在 Firefox 中。但是如果有一种方法可以在两种浏览器中都有效,那还是不错的。

回答by Joeri Sebrechts

Try Date.now().

试试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.

跳过很可能是由于垃圾收集。通常可以通过尽可能多地重用变量来避免垃圾收集,但我不能具体说明可以使用哪些方法来减少垃圾收集暂停。

回答by Chris GW Green

I know this is a pretty old thread, but to keep things up to date and more relevant, you can use the more accurate performance.now()functionality to get finer grain timing in javascript.

我知道这是一个很旧的线程,但是为了使事情保持最新和更相关,您可以使用更准确的performance.now()功能在 javascript 中获得更精细的计时。

window.performance = window.performance || {};
performance.now = (function() {
    return performance.now       ||
        performance.mozNow    ||
        performance.msNow     ||
        performance.oNow      ||
        performance.webkitNow ||            
        Date.now  /*none found - fallback to browser default */
})();

回答by ngryman

As far that I know you only can get time with Date.

据我所知,您只能在Date 上获得时间。

Date.nowis the solution but is not available everywhere : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now.

Date.now是解决方案,但并非随处可用:https: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now

var currentTime = +new Date();

This gives you the current time in milliseconds.

这以毫秒为单位为您提供当前时间。

For your jumps. If you compute interpolationscorrectly according to the delta frame timeand you don't have some rounding number error, I bet for the garbage collector (GC).

为了你的跳跃。如果您根据增量帧时间正确计算插值并且您没有一些舍入数字错误,我敢打赌垃圾收集器(GC)。

If there is a lot of created temporary object in your loop, garbage collection has to lock the thread to make some cleanup and memory re-organization.

如果循环中有很多创建的临时对象,垃圾收集必须锁定线程以进行一些清理和内存重组。

With Chrome you can see how much time the GC is spending in the Timelinepanel.

使用 Chrome,您可以在Timeline面板中查看 GC 花费了多少时间。

EDIT: Since my answer, Date.now()should be considered as the best option as it is supported everywhere and on IE >= 9.

编辑:因为我的回答,Date.now()应该被认为是最好的选择,因为它在任何地方和 IE >= 9 上都得到支持。

回答by dilip kumar

If you have date object like

如果你有像这样的日期对象

var date = new Date('2017/12/03');

then there is inbuilt method in javascript for getting date in milliseconds format which is valueOf()

然后在javascript中有内置方法用于以毫秒格式获取日期,即valueOf()

date.valueOf(); //1512239400000 in milliseconds format

回答by LarsKnudsen

This is a very old question - but still for reference if others are looking at it - requestAnimationFrame()is the right way to handle animation in modern browsers:

这是一个非常古老的问题 - 但如果其他人正在查看它仍然可以参考 -requestAnimationFrame()是在现代浏览器中处理动画的正确方法:

UPDATE: The mozilla link shows how to do this - I didn't feel like repeating the text behind the link ;)

更新:mozilla 链接显示了如何执行此操作 - 我不想重复链接后面的文字;)