【问题标题】:Pause javascript until a function has been executed暂停javascript,直到一个函数被执行
【发布时间】:2013-10-17 16:50:18
【问题描述】:

我正在尝试学习如何编写 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 毫秒的延迟

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

【问题讨论】:

  • 循环永远不会退出。正如您在上一个问题中所解释的,在浏览器返回主事件循环之前不会创建窗口。
  • 代码看起来不是很javascripty
  • 任何依赖于窗口创建的东西都应该在回调函数中。你已经在另一个问题中被告知过。
  • 另外,循环条件使用=而不是=====,这是一个赋值。无论数组做什么,这始终是正确的。

标签: javascript asynchronous google-chrome-extension google-chrome-app


【解决方案1】:

只需在回调中使用 myArray:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      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
      }
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-05
          • 2016-09-08
          • 1970-01-01
          相关资源
          最近更新 更多