2

This works:

document.getElementById("2").innerHTML =  new Date().getTime() - startDelay ;

var startDelay; //global scope
startDelay = new Date().getTime(); //this is done inside of a function

this also works

document.getElementById("2").innerHTML = startDelay + " " + startTime ;
var startTime; //global scope
startTime = new Date().getTime(); //this is done in another function

//For some odd reason this does NOT work :/

document.getElementById("2").innerHTML =  new Date().getTime() - startDelay + " " + new Date().getTime() - startTime;

Running this in chrome: This gives me a single NAN

document.getElementById("2").innerHTML = 1 + " " + new Date().getTime() - startTime;

This also gives me a NAN error!

DR. Palson_PH.d
  • 301
  • 1
  • 3
  • 11

2 Answers2

5

whole expression new Date().getTime() - startDelay + " " + new Date().getTime() - startTime;

It starts with

new Date().getTime() - startDelay

which, given startDelay definition, is the same as

new Date().getTime() - new Date().getTime();

This will give you a number. When you add the number, you try to add a string with a space, in this part of the code:

.. - startDelay + " "

Now the expression becomes a string. Since your string ends with an empty space, when you add this

.. + new Date().getTime()

You get something like this

"1489700484842 1489700484842"

You can tell there's an empty space in the middle.

To that string, if you do - startTime; sure you won't get a number

Jerfov2
  • 5,264
  • 5
  • 30
  • 52
Gonzalo.-
  • 12,512
  • 5
  • 50
  • 82
4

You are mixing data types. Try using parens to ensure the math operations complete before the data coerces to string:

(new Date().getTime() - startDelay) + " " + (new Date().getTime() - startTime);

NaN error means "Not a number." It is a type error because JS engine thinks you are trying to "subtract strings" which isn't a valid operation.

John Vandivier
  • 2,158
  • 1
  • 17
  • 23