0

I am trying to pass the variable I get from chrome.storage.local.get to another global variable delayMilliSeconds so I can use it in multiple functions. I know that the delay is only inside the scope of chrome.storage.local.get and is asynchronous, however, is there a way to pass this outside the scope?

var delay;
chrome.storage.local.get('updateDelayValueTo', function(result){
    delay = result.updateDelayValueTo; //I am getting this correctly
    console.log("delay is: " + delay); //10000
});

function runMyCalculation() {
    var delayMilliSeconds = Math.floor((Math.random() * delay) + 1);
    // Run other code/functions, which depends on "delayMilliSeconds"
    functionOne(delayMilliSeconds);
}


functionOne(delayMilliSeconds) {
    //use delayMilliSeconds here 
    if(functionTwo()){
        setTimeout(functionOne,delayMilliSeconds);
        console.log("delay in here is: " + delayMilliSeconds);
    }
}

functionTwo() {
    //and here..
    while(ButtonIsClicked){ 
        console.log("delay in here is: " + delayMilliSeconds);
        ButtonIsClicked logic...
    }
}


console.log
delay down here is: 260
09:36:22.812 content_script.js:83 delay down here is: 260
09:36:22.813 content_script.js:15 delay is: 1000
09:36:23.074 content_script.js:79 delay down here is: undefined
09:36:23.087 content_script.js:83 delay down here is: undefined
09:36:23.089 content_script.js:79 delay down here is: undefined
09:36:23.089 content_script.js:83 delay down here is: undefined
tiger_groove
  • 956
  • 2
  • 17
  • 46

1 Answers1

0

You should set delayMilliSeconds only after have got result.updateDelayValueTo value.

This should work:

var delay; 

chrome.storage.local.get('updateDelayValueTo', function(result){
    delay = result.updateDelayValueTo; 
    runMyCalculation();
});

function runMyCalculation() {
    var delayMilliSeconds = Math.floor((Math.random() * delay) + 1);
    // Run other code/functions, which depends on "delayMilliSeconds"
}
Denis L
  • 3,209
  • 1
  • 25
  • 37
  • Does the delay variable only get stored once? I noticed that when I pass the `delay` variable function into another function that has a while loop, the console.log shows the correct number on first iteration, however, after first iteration the values changes back to undefined. – tiger_groove Aug 25 '17 at 16:30
  • It should stay defined unless you change the variable value in another place. But it hard to say without code example. – Denis L Aug 25 '17 at 16:39
  • I updated my code above – tiger_groove Aug 25 '17 at 16:43