Javascript: attempting to access variable outside of function getting 'undefined' -
i trying access time_pressed variable outside of function held() returning time_pressed , doing console.log(held()) outside of function. console.log-ing undefined. why not working , how can need access said variable outside of function?
here code..
function held(){ var time_pressed; document.onmousedown = function(e){ mousedown_time = gettime(); console.log(mousedown_time); } document.onmouseup = function(e){ time_pressed = gettime() - mousedown_time; console.log('you held mouse down for', time_pressed,'miliseconds.'); } return time_pressed } console.log(held())
consider following function:
function held(){ var time_pressed; return time_pressed; } console.log(held()); what expect function return? no value has been defined, value undefined.
the thing(s) you're doing in function assigning event handler functions document. means 2 things:
- those separate functions , they return isn't this returns.
- those functions won't executed until some later time when occurs.
you're creating event handlers. it's not clear why you're trying log returned value. function you're executing doesn't return anything, nor need to. there's nothing logged. event handlers log console when they execute.
Comments
Post a Comment