0

I am new to javascript, and I need to calculate the difference between 2 timestamps (in seconds). one is when the user clicks on the first card, the other one is when he clicks on the last one.

my code:

var startTime = Date.now();
var endTime = Date.now();
var currentResult = ((endTime - startTime)/1000);

this gives NaN in the console, but I can see the long numbers if I do:

console.log(startTime);
console.log(endTime);

even when I use:

var startMillsecond = parseInt(startTime, 10);
var endMillsecond = parseInt(endTime, 10);

and then calculate:

currentResult = ((endMillsecond - startMillsecond)/1000);

it gives NaN as well. What am I doing wrong? I need to use only javascript.. Thanks for the help!

Maya
  • 23
  • 3
  • Possible duplicate of [Get difference between 2 dates in JavaScript?](https://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript) – brrwdl Dec 02 '17 at 17:05
  • 3
    Don't see how you can possibly get NaN from what is shown. Provide a [mcve] that reproduces it – charlietfl Dec 02 '17 at 17:06

1 Answers1

0

Date.now() returns a floating point number representing a number of miliseconds. Subtracting of from the other then dividing by 1000 gives a number of seconds. So this works:

var startTime = Date.now();
setTimeout(function() {
  var endTime = Date.now();
  var currentResult = ((endTime - startTime) / 1000);
  console.log(currentResult)
}, 3125);

IOW, you're doing something else than you posted.

André Werlang
  • 5,839
  • 1
  • 35
  • 49
  • Thank you for your answer. I understand where is the mistake. the startTime was not declared outside the function, so when I tried to do the difference it gave a mistake (the function runs every time the user clicks on a card). Thank you – Maya Dec 02 '17 at 18:38