Reputation: 1669
While I define the starttime
variable without the var
keyword thus making it global, logging the starttime
in console gives undefined
.
starttime = new Date();
setInterval(function(starttime){
getTimeElapsed(starttime);
}, 1000);
How can I access the starttime
variable inside the function?
Upvotes: 1
Views: 67
Reputation: 943651
You have two variables called starttime
.
One global, implicitly declared here:
starttime = new Date();
and one local, declared here:
function(starttime){
Since you don't use the local version, the best approach is to remove that declaration.
setInterval(function(){
Alternatively, access the global explicitly:
getTimeElapsed(window.starttime);
Upvotes: 2
Reputation: 53958
You could try the following:
starttime = new Date();
setInterval(function(){
getTimeElapsed(starttime);
}, 1000);
Now you access the global declared variable starttime
. While in your code, you were accessing an undefined variable. Why? You function had one argument that you never passed to it. So it's value was undefined.
Upvotes: 3