2017-08-10 43 views
1

我刚刚开始在web上下文中使用JavaScript,但我还没有完全围绕回调函数,但我认为在我目前的场景中,我将需要一个(或更多?)。如何在while循环中处理交替异步函数?

我有两个函数需要反复交替运行,直到满足某个条件(条件本身取决于函数2以某种方式更改全局变量,不确定是否相关)。

所以最初我尝试这样做:

while(condition !== true) { 
    function1(); 
    function2(); 
} 

然而,这并不因为两者的工作函数都利用了setInterval函数来处理每一个动画等while循环执行一切都太快了(!)并不等待功能完成。现在我知道了,据说我需要在函数中使用回调函数。然而,因为function2()需要等待function1()function1()之后需要等待function2(),我不太清楚如何在这里使用回调,因为我认为这需要某种无限的回调链。

如果这会有所帮助,用伪代码,此刻整个设置是这样的(假设它等待一个全局变量来达到一定的指标):

var myGlobalCounter = 0; 

while(myGlobalCounter < 8) { 
    doSomeStuff(400); 
    doSomeMoreStuff(400); 
} 


function doSomeStuff(targetCount) { 
    // first function that needs setInterval 
    var localCount = 0; 

    myInterval = setInterval(function(){ 
    if (localCount !== targetCount) { 
     count += 1; 
     // animation happening here 
    } else { 
     clearInterval(myInterval); 
    } 
    },20); 
} 

function doSomeOtherStuff(targetCount) { 
    // second function that needs setInterval and alters the global counter 
    var localCount = 0; 

    myInterval = setInterval(function(){ 
    if (localCount !== targetCount) { 
     localCount += 1; 
     // another animation happening here 
     myGlobalCounter += 1; 
    } else { 
     clearInterval(myInterval); 
    } 
    },20); 
} 

我怎样才能解决这个问题建立?请记住,我是一个初学者,我希望在普通JavaScript中使用一个解决方案,因为我已经设法避免了jQuery到目前为止的其他项目,并且对在while循环中使用回调的底层逻辑感兴趣。

回答

2

根据条件交替两个函数。您可以将条件和函数传递给对方。

function function1(condition, otherFunction) { 
    // code 
    if(!condition) otherFunction(condition, function1); 
} 

function function2(condition, otherFunction) { 
    // code 
    if(!condition) otherFunction(condition, function2); 
} 
+0

谢谢,这个作品完美。比我想到的奇怪的解决方案容易得多! – mdomino

+0

不客气!很高兴我能帮上忙。 – Anthony