use*_*728 5 javascript jquery javascript-events
我有很多功能需要连续运行,但不能在另一个功能完成之前运行.我需要的是一种方法,将这些函数排队,只有在上一个函数成功完成后才能运行.有任何想法吗?
Function1();
Function2();
Function3();
Function4();
Function5();
Run Code Online (Sandbox Code Playgroud)
你可以使用这样的东西:
var FunctionQueue = (function(){
var queue = [];
var add = function(fnc){
queue.push(fnc);
};
var goNext = function(){
var fnc = queue.shift();
fnc();
};
return {
add:add,
goNext:goNext
};
}());
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
var fnc1 = function(){
window.setTimeout(function(){
alert("1 done");
FunctionQueue.goNext();
}, 1000);
};
var fnc2 = function(){
window.setTimeout(function(){
alert("2 done");
FunctionQueue.goNext();
}, 5000);
};
var fnc3 = function(){
window.setTimeout(function(){
alert("3 done");
FunctionQueue.goNext();
}, 2000);
};
FunctionQueue.add(fnc1);
FunctionQueue.add(fnc2);
FunctionQueue.add(fnc3);
FunctionQueue.goNext();
Run Code Online (Sandbox Code Playgroud)
几年后编辑:人们接近这个的另一种方式是传递一个next你可以调用以继续链的功能.像这样:
var Queue = function(arr){
var index = 0;
var next = function(){
if (index >= arr.length) {return;}
arr[index++](next);
};
return next;
};
var fn1 = function(next){
console.log("I am FN1");
next();
};
var fn2 = function(next){
console.log("I am FN2");
setTimeout(next,1000);
};
var fn3 = function(next){
console.log("I am FN3");
setTimeout(next,3000);
};
var fn4 = function(next){
console.log("I am FN4");
setTimeout(next,1000);
};
Queue([fn1, fn2, fn3, fn4])();
Run Code Online (Sandbox Code Playgroud)
您可以创建一个队列功能:
function Queue(arr) {
var i = 0;
this.callNext = function() {
typeof arr[i] == 'function' && arr[i++]();
};
}
Run Code Online (Sandbox Code Playgroud)
所以如果这些是你的功能......
function f1() {
alert(1);
}
function f2() {
alert(2);
}
function f3() {
alert(3);
}
Run Code Online (Sandbox Code Playgroud)
...你只需在新的Queue实例中传递它们(它们的引用):
var queue = new Queue([f1, f2, f3]);
Run Code Online (Sandbox Code Playgroud)
然后执行callNext()以按顺序调用函数:
queue.callNext();
queue.callNext();
queue.callNext();
Run Code Online (Sandbox Code Playgroud)
现场演示: http ://jsfiddle.net/CEdPS/3/
为什么不完全按照您所展示的那样,将它们列在覆盖函数中呢?
function do_1_to_5() {
Function1();
Function2();
Function3();
Function4();
Function5();
}
Run Code Online (Sandbox Code Playgroud)
如果您的函数包含 AJAX 调用,那么您需要将它们挂接到处理 AJAX 调用的回调函数的末尾。
| 归档时间: |
|
| 查看次数: |
4284 次 |
| 最近记录: |