【问题标题】:How to handle alternating asynchronous functions in a while loop?如何在while循环中处理交替的异步函数?
【发布时间】:2018-01-18 23:13:58
【问题描述】:

我刚开始在网络环境中使用 JavaScript,我还不能完全理解回调函数,但我认为在我目前的情况下,我需要一个(或更多?)。

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

所以最初我尝试了这个:

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 循环中使用回调的底层逻辑感兴趣。

【问题讨论】:

    标签: javascript asynchronous recursion callback


    【解决方案1】:

    根据条件交替使用两个函数。您可以将条件和函数相互传递。

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

    【讨论】:

    • 谢谢,这很好用。比我考虑的奇怪解决方案要容易得多!
    猜你喜欢
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 2019-07-04
    相关资源
    最近更新 更多