Better way of getting time in milliseconds in javascript?

前端 未结 5 1096
说谎
说谎 2021-01-30 05:06

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 e

相关标签:
5条回答
  • 2021-01-30 05:11

    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.

    0 讨论(0)
  • 2021-01-30 05:17

    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:

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

    0 讨论(0)
  • 2021-01-30 05:25

    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()

    date.valueOf(); //1512239400000 in milliseconds format
    
    0 讨论(0)
  • 2021-01-30 05:30

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

    Date.now is the solution but is not available everywhere : 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 interpolations correctly according to the delta frame time and you don't have some rounding number error, I bet for the garbage collector (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 Timeline panel.

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

    0 讨论(0)
  • 2021-01-30 05:35

    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.

    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 */
    })();
    
    0 讨论(0)
提交回复
热议问题