dart

What is more precise than a new DateTime in a Dart web app?


Getting a new DateTime isn't accurate enough for me. A date object in the browser gives me milliseconds as an integer. I'd like to be able to get a time that's more precise than the standard date object. Is this possible? How can I do this?


Solution

  • Use window.performance.now() to get a monotonic, high-resolution time. The now() function returns a double with microseconds in the fractional.

    Here is an example:

    import 'dart:html';    
    main() {
      var time = window.performance.now();
      print(time); // 12123.24341221
    }
    

    Notice that now() is not the typical "time from the epoch". Instead, it is a delta from window.performance.timing.navigationStart.

    The navigationStart field is defined as (from the spec):

    This attribute must return the time immediately after the user agent finishes prompting to unload the previous document. If there is no previous document, this attribute must return the same value as fetchStart.

    The window.performance.now() timestamp is great because it's not affected by clock skew and is more accurate than getting a new DateTime.

    If your application is driven by requestAnimationFrame (and if not, why not? :) then you already have a high resolution timestamp!

    The Future returned by animationFrame completes with a high resolution timestamp:

    Future<num> animationFrame;
    

    You can use it like this:

    gameLoop(num highResolutionTime) {
       // stuff
       window.animationFrame.then(gameLoop);
    }
    
    main() {
       window.animationFrame.then(gameLoop);
    }