-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); 
    } 
); 
相关问题