如何执行函数块
How to execute blocks of functions?
这是我的代码:
var testStacks = new Array();
function test(elem) {
console.log(elem);
... asynch operations
}
testStacks.push(test("hello 0"));
testStacks.push(test("hello 1"));
testStacks.push(test("hello 2"));
testStacks.push(test("hello 3"));
testStacks.push(test("hello 4"));
// init first 3 functions
testStacks[0];
testStacks[1];
testStacks[2];
我想一次执行3个功能。因此hello 0
、hello 1
和hello 2
在开始时一起开始。然后,一旦一个函数完成(它们执行异步操作),它就必须从数组中调用下一个函数(尚未执行)。等等…
似乎testStacks[0]
什么都不做,当我推送函数时,它就会被执行。
我该怎么做?(我想避开setInterval()
)。
一个简单的方法可以是同时推送函数和参数。
var testStacks = new Array();
function test(elem) {
console.log(elem);
... asynch operations
}
testStacks.push({func: test, param: "hello 0"});
testStacks.push({func: test, param: "hello 1"});
testStacks.push({func: test, param: "hello 2"});
testStacks.push({func: test, param: "hello 3"});
testStacks.push({func: test, param: "hello 4"});
// init first 3 functions
testStacks[0].func(testStacks[0].param);
testStacks[1].func(testStacks[1].param);
testStacks[2].func(testStacks[2].param);
当然,这可以用很多方法概括和清理,但应该给你一个基本的想法。
您正在执行函数并推送返回值。推送一个函数:
testStacks.push(function(){ test("hello 0"); });
无论选择什么解决方案,都需要第三方对象来管理当前调用堆栈,以及在操作完成时通知该对象的方法。关于以下(相当脏的)代码,我决定使用一个从test
函数调用的简单回调:
var Stack = function (maxCalls, stack) {
this.ongoing = 0;
this.maxCalls = maxCalls;
Array.prototype.push.apply(this, stack);
this.next(); // starts immediately
};
Stack.prototype = Object.create(Array.prototype);
Stack.prototype.next = function () {
var me = this;
while (this.length && this.ongoing < this.maxCalls) {
this.ongoing++;
// calls the next function
// passing a callback as a parameter
this.shift()(function () {
me.ongoing--;
me.next();
});
}
};
有关使用案例,请参阅此演示:http://jsfiddle.net/wared/5eu8b/.正如您所看到的,函数是以先进先出的方式一个接一个地调用的,但它们以任何顺序完成。
希望它能有所帮助:)
相关文章:
- 等待回调函数执行
- 暂停函数执行流程,直到ajax请求完成
- Bigcommerce-是否可以在函数执行后更改文本
- 如何对jquery中的未命名函数执行.call()
- 等待函数执行后再继续
- mootools类型的函数将文本作为函数执行
- 停止从另一个函数执行Javascript函数
- Jquery回调函数执行多次
- 如何使即兴 jquery 暂停当前函数执行
- JavaScript 双函数执行
- 来自函数 Javascript 的 NaN 返回值 ||函数执行顺序
- 如何在 JS 中调用 2 次或更多次时延迟函数执行
- 函数执行的次数超出预期
- JS中函数执行错误
- 为什么这个函数执行了两次
- 从子函数执行父函数;t更新父级'的属性
- 如何在jQuery函数执行's处于活动状态
- 使用javascript函数执行php文件
- jQuery函数执行顺序
- javascript中同步函数执行中的问题