暂停 javascript,直到函数被执行

Pause javascript until a function has been executed

本文关键字:函数 执行 javascript 暂停      更新时间:2023-09-26

我正在尝试学习如何编写chrome扩展程序。但是,我在异步编程方面没有很多经验,这给我带来了问题。

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 毫秒的延迟

什么效果最好? 是否有内置函数来处理这种情况?

只需在回调中使用 myArray:

chrome.windows.create(
    newWindow,
    function(t)
    {
        myArray.push(t);
        //Do your length check here
        if ( myArray.length === completeLength ) doMyAction( myArray );
    }
);

使用延迟功能执行。我在我的项目中在这种情况下使用了相同的方法。

就个人而言,我建议不要使用间隔来轮询新项目。使其成为回调的一部分。

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
}

var t=setTimeout(function(){alert("10 minutes Complete")},10000)