0

I`m a beginner reading a tutorial about Dates in JavaScript, and it gives this example to compare the time between two events.

I don't really understand why firstDate and var secondDate wouldn't be the exact same time? does the new Date object in var secondDate only take the time once doEvent is triggered, whereas firstDate takes the time with window.onload?

Also, why would the variable firstDate not have the "var" tag, while variable secondDate does? would that be just a typo by the author, or is it significant in some way?

var firstDate;
window.onload=startTimer;

function startTimer(){
 firstDate = new Date();
 document.getElementById("date").onclick=doEvent;
}

function doEvent() {
 var secondDate = new Date();
 alert((secondDate - firstDate) / 1000);
}
1
  • 1
    Ofcourse new Date object in var secondDate only take the time once doEvent is triggered, because writing a method in succession of another method does not execute it, rather it is executed on the event it is bind to. Commented Mar 1, 2011 at 5:06

1 Answer 1

3

Your guess is exactly correct. firstDate is the time when the window.load event fires, and secondDate is the time when the element with id date is clicked.


In re: your edit, there is a var to go with the firstDate as well - it's outside of the scope of startTimer. It is not a typo. firstDate needs to be defined outside of the scope of the startTimer and doEvent functions so that it has a meaningful value inside of the doEvent function.

It might be useful for you to read up on JavaScript scoping.

Sign up to request clarification or add additional context in comments.

4 Comments

o.k., thanks. Can you answer the second question I just added to the OP about why firstDate has no var tag whereas the secondDate does?
thank you. why didn`t var secondDate need to be defined outside the scope of the functions?
@mjmitche: because it does not need to be used outside of doEvent.
thanks, so if firstDate was only defined inside of startTimer, it would have worked in that function, but not in doEvent? appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.