3

I have the below code,

it is running however the output in the console is

instant: true
instant2: false

as the variable is not being overwritten in the global scope. How can I access the variable in the global scope?

var instant = false;
$('document').ready(function(){
  chrome.extension.sendRequest({
    action: "getStorage",
    key: "instant"
  }, function(response) {
    instant = true;
    console.log('instant: ', instant); 
  });
  console.log('instant2: ', instant);
});

2 Answers 2

6

It is getting overridden, but later. Your function(response) isn't getting executed until after the outer function returns.

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

3 Comments

It depends what you are trying to do. If you want a local version of instant, declare it with var, i.e. var instant = true;.
Actually I just want to use the variable in a global scope after this has completed.
What I am doing at the moment to fix it is to move all other code inside of the callback. but it is messy.
0

window.instant should get you the value of your global variable.

1 Comment

Not after the line instant = true is executed. Without var preceding it, that will overwrite the global variable.

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.