0

Why is MM_SYSTEM_RESTART_SECONDS undefined in the following snippet?

If var MM_SYSTEM_RESTART_SECONDS = 40; is put inside the function, then MM_SYSTEM_RESTART_SECONDS is 40, but if outside the function, then MM_SYSTEM_RESTART_SECONDS is always undefined.

var MM_SYSTEM_RESTART_SECONDS = 40;


function wait_until_MM_restarts()
{
    restart_timeout_start_seconds = get_cookie( "restart_timeout_start_seconds" )
    elapsed_restart_seconds =  elapsed_seconds( restart_timeout_start_seconds )
    append_debug_message( elapsed_restart_seconds + "/" +   MM_SYSTEM_RESTART_SECONDS )
    if( elapsed_restart_seconds > MM_SYSTEM_RESTART_SECONDS )
11
  • 3
    It shouldn't be. I can think of things that might cause that effect … but would have to see the rest of the function to tell. It is usually a good idea to provide snippets of code that can be run to demonstrate the problem. Commented Mar 7, 2012 at 0:13
  • I think you have to provide some more context. Better, create a jsfiddle.net demo. Commented Mar 7, 2012 at 0:14
  • I tend to avoid globals. I understand your interest in why this is happening, it's a good question (+1). However, I would pass MM_SYSTEM_RESTART_SECONDS into the wait_until_MM_restarts() function as a parameter. Commented Mar 7, 2012 at 0:20
  • Chances are pretty good that MM_SYSTEM_RESTART_SECONDS is defined in some other scope (inside some other function) and isn't available from this function because as you've shown it here, it would work just fine. Commented Mar 7, 2012 at 0:21
  • It seems to work with this attempt at a demo: jsfiddle.net/qUhQV I second @jfriend00's suggestion that there's a possibility it's a scope problem. Commented Mar 7, 2012 at 0:24

1 Answer 1

2

This just bit me. If you call the function before/above the variable declaration the variable might be undefined.

For example

f("before");

var value = 99;
function f(msg)
{    
  alert("msg=" + msg + " value=" + value);
}

f("after");

results in:

msg=before value=undefined
msg=after value=99

http://jsfiddle.net/qUhQV/4/

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

Comments

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.