暂停 javascript,直到函数被执行
Pause javascript until a function has been executed
我正在尝试学习如何编写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)
相关文章:
- 等待回调函数执行
- 暂停函数执行流程,直到ajax请求完成
- Bigcommerce-是否可以在函数执行后更改文本
- 如何对jquery中的未命名函数执行.call()
- 等待函数执行后再继续
- mootools类型的函数将文本作为函数执行
- 停止从另一个函数执行Javascript函数
- Jquery回调函数执行多次
- 如何使即兴 jquery 暂停当前函数执行
- JavaScript 双函数执行
- 来自函数 Javascript 的 NaN 返回值 ||函数执行顺序
- 如何在 JS 中调用 2 次或更多次时延迟函数执行
- 函数执行的次数超出预期
- JS中函数执行错误
- 为什么这个函数执行了两次
- 从子函数执行父函数;t更新父级'的属性
- 如何在jQuery函数执行's处于活动状态
- 使用javascript函数执行php文件
- jQuery函数执行顺序
- javascript中同步函数执行中的问题