-1

Need to check time execution on client side

var start = new Date().getSeconds();
// code...
var end = new Date().getSeconds();
let time = end - start
console.log(time);

Result: 0;

I suppose it's a part of second, for example 0.05. How can I get it?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • 4
    `Date.now()` gives you milliseconds (thousandths of a second) since The Epoch (midnight Jan 1st 1970 GMT). `performance.now()` gives you the same thing, theoretically with higher precision (through fractional numbers) although most browsers dialled that back after Spectre and Meltdown. There's also `console.time("label")` and `console.timeEnd("label")`, which report the interval between them. – T.J. Crowder Mar 28 '19 at 08:20
  • 2
    Seconds are not a fine enough unit to measure this. Using `Date().getTime() - Date().getTime()` will give you the difference in milliseconds. – Brian Peacock Mar 28 '19 at 08:22
  • In addtion to not being fine-grained enough, getSeconds() returns the number of seconds since the start of the current minute. If you start the timer shortly before the end of a minute, and finish early in the next minute, the second value can be smaller. Most of the time you will just get 0 or 1 as the result, but it could -58 or -59 as well. – T G Mar 31 '19 at 06:53

1 Answers1

0

Use getTime() instead of getSeconds() and divide the difference by 1000.

var start = new Date().getTime();
for(let i = 0;i<100000;i++)
var end = new Date().getTime();
let time = (end - start)/1000
console.log(time);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73