简体   繁体   中英

Javascript: While the variable is declared in global scope, it remains undefined inside the function

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?

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM