Posted By

noah on 09/24/07


Tagged

time performance optimization profiling


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

vali29
korzhik


Get the time elapsed between two intervals


 / Published in: JavaScript
 

  1. var foo = new Date();
  2. var bar = new Date();
  3. var baz = new Date();
  4. baz.setTime(bar.getTime() - foo.getTime());
  5. alert(baz.getMilliseconds() + " ms elapsed between the definition of foo and bar.");

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: meetar on May 16, 2011

This is incorrect!

getMilliseconds() returns the number of milliseconds into the current second of the timestamp contained by the Date(), like a modulo (%) for milliseconds. If used with an unset Date() object, it will return the number of milliseconds into the current second of the current clock time. So this code will only return a number from 0-999.

You can check this with this code:

var foo = new Date(); setTimeout( function() { var bar = new Date(); var baz = new Date(); baz.setTime(bar.getTime() - foo.getTime()); alert(baz.getMilliseconds() + " ms elapsed between the definition of foo and bar."); }, 2500);

The result will be close to 500, instead of 2500.

Here's a better way to do it:

var foo = new Date(); var bar = new Date(); var diff = bar - foo; alert(diff + " ms elapsed between the definition of foo and bar.");

You need to login to post a comment.