2017-08-25 421 views
0

我试图传递变量我从chrome.storage.local.get到达另一个全局变量delayMilliSeconds这样我就可以在多种功能中使用它。我知道delay只是内部chrome.storage.local.get的范围和是异步的,但是,有没有办法通过这个范围之内?的Javascript传递一个变量chrome.storage.local.get到另一个变量

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 
+0

如果我们声明'delay'外'chrome.storage.local.get'和内部分配的值,所以它服务的价值出方的范围。 – Amogh

+0

或者干脆写一个全局函数从铬存储返回值,并用它每一个地方... – Amogh

+0

@Amogh你能告诉我你的第二个方法的一个例子。 – kkmoslehpour

回答

-1

您是否尝试过使用window.delay = result.updateDelayValueTo;所以你专门赋值给窗口对象?

0

您应该设置delayMilliSeconds后才能已经得到result.updateDelayValueTo值。

这应该工作:

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" 
} 
+0

延迟变量是否只存储一次?我注意到,当我通过'delay'变量函数到具有while循环的另一个功能,执行console.log显示了第一次迭代正确的号码,但是,更改值回undefined一次迭代后。 – kkmoslehpour

+0

它应该保持定义,除非你改变在另一个地方的变量值。但很难说没有代码的例子。 – Deliaz

+0

我更新了上面的代码 – kkmoslehpour