2017-08-25 417 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