如何使用JS / jQuery对setTimeout设置的几个函数进行排队 [英] How to queue several functions set by setTimeout with JS/jQuery
问题描述
我在JS上有一个工作流程,它应该逐个由setTimeout函数运行几个。如何使用JS / jQuery,最好以一些简单而美观的方式完成?
I have a workflow on JS, which should run several set by setTimeout functions one by one. How this could be done with JS/jQuery, preferably in some easy and beautiful way?
看起来像这样
function recursiveOne(arg1){
if (allRight) return;
doSomething();
andAnotherOne();
setTimeout(function(){recursiveOne(arg1)}, 3000);
}
function coreFunction(){
recursiveOne(arg1);
recursiveTwo(arg2);
recursiveThree(arg3);
}
其中recursiveTwo只有在recursiveOne已经完成最后一次迭代时才会启动。
where recursiveTwo should start only when recursiveOne already done its last iteration.
坏部分是所有函数都通过setTimeout工作,因为我需要等待来自后端的反应,并且无法直接接收它 - 只能通过HTML源。
The bad part is all functions work through setTimeout because I need to wait reaction from backend, and couldn't receive it directly - only by HTML source.
我可以看到可能的解决方案:
Possible solutions, that I could see:
- 在上一个函数中传递的下一个函数回调。不太酷。
- jQuery deffered对象,它不是那么美丽,但更好一点。缺点是我仍然应该在每个我希望使用这种方式的函数中增加额外的deffered请求。
推荐答案
您必须直接使用回调或调用 coreFunction
。下面你可以找到一种使用函数数组的方法。
You have to use a callback or invoke coreFunction
directly. Below you can find a way to do it using array of functions.
function recursiveOne(arg1){
if(arg1 < 5){
arg1++;
setTimeout(function(){recursiveOne(arg1);}, 500);
}else{
console.log("func1 complete");
coreFunction();
}
}
function recursiveTwo(arg1){
if(arg1 < 10){
arg1++;
setTimeout(function(){recursiveTwo(arg1);}, 500);
}else{
console.log("func2 complete");
coreFunction();
}
}
function recursiveThree(arg1){
if(arg1 < 20){
arg1++;
setTimeout(function(){recursiveThree(arg1);}, 500);
}else{
console.log("func3 complete");
coreFunction();
}
}
var funcSet = [recursiveOne, recursiveTwo, recursiveThree];
var funcArgs = [[1], [5], [10]];
function coreFunction(){
if(funcSet.length){
var func = funcSet.shift();
func.apply(window, funcArgs.shift())
}
}
coreFunction();
这篇关于如何使用JS / jQuery对setTimeout设置的几个函数进行排队的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!