-3

我在學習如何編寫一個Chrome擴展。但是,我沒有太多的異步編程經驗,並且導致了我的問題。暫停JavaScript,直到執行一個函數

chrome.windows.create(newWindow, function(t){myArray.push(t);}); 
// When I call myArray next it has not yet updated. 

我該如何解決這個問題?

我有一個while循環的一些想法

地說:

int tempLength = myArray.length; 
chrome.windows.create(newWindow, function(t){myArray.push(t);}); 
While (tempLength = myArray.length) 
{ 
    //nothing 
} 
// call myArray 

或添加chrome.windows.create

後10毫秒的延遲什麼工作最好?是否有一個函數來處理這種情況?

+0

循環將永遠不會退出。正如您在上一個問題中所解釋的那樣,在瀏覽器返回到主事件循環之前,窗口創建不會發生。 – Barmar

+0

代碼看起來不怎麼樣javascripty – ajax333221

+1

任何依賴窗口創建的東西都應該在回調函數中。你在另一個問題中已經被告知了這一點。 – Barmar

回答

0

使用延遲功能執行。我在我的項目中使用過這種情況。

-1

變種T = setTimeout的(函數(){警報( 「10分鐘內完成」)},10000)

0

個人而言,我建議不要使用的間隔輪詢一個新的項目。使其成爲回調的一部分。

var myArray = []; 
chrome.windows.create(newWindow, 
    function(t){ 
    myArray.push(t); 
    processNewItem(t); 
    }); 

// Do not continue code execution at this point. Let the callback initiate the processing. 


function processNewItem(t){ 
    //do whatever in here 
} 
1

只要讓你的myArray的使用回調中:

chrome.windows.create(
    newWindow, 
    function(t) 
    { 
     myArray.push(t); 

     //Do your length check here 
     if (myArray.length === completeLength) doMyAction(myArray); 
    } 
); 
相關問題