Cross-browser, high resolution timer function (replacement for Date().getTime()).


/ Published in: JavaScript
Save to your folder(s)

A cross-browser Javascript shim function to return the number of milliseconds elapsed since either the browser navigationStart event (using performance.now or browser equivalent) or the UNIX epoch, depending on availability.
Use it to get more accurate performance timings when optimizing your code.


Copy this code and paste it in your HTML
  1. var now = (function() {
  2.  
  3. // Returns the number of milliseconds elapsed since either the browser navigationStart event or
  4. // the UNIX epoch, depending on availability.
  5. // Where the browser supports 'performance' we use that as it is more accurate (microsoeconds
  6. // will be returned in the fractional part) and more reliable as it does not rely on the system time.
  7. // Where 'performance' is not available, we will fall back to Date().getTime().
  8.  
  9. var performance = window.performance || {};
  10.  
  11. performance.now = (function() {
  12. return performance.now ||
  13. performance.webkitNow ||
  14. performance.msNow ||
  15. performance.oNow ||
  16. performance.mozNow ||
  17. function() { return new Date().getTime(); };
  18. })();
  19.  
  20. return performance.now();
  21.  
  22. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.