Javascript 函数在上一个函数完成之前执行

Javascript function executing before previous function is completed

我在使用以下代码时遇到了一些问题。这是我正在调用的函数,用于在我正在开发的简单游戏的某些资产上创建淡入和淡出动画,使用出色的 CreateJS 库。我需要为一项资产 运行 一次此代码,然后在第一个功能完成后 运行 将其覆盖在另一项资产上。函数如下:

    function fadeInOut(asset, duration, stage)
    {
      stage.addChild(asset)
      let fadeInOut = setInterval(function()
      {
        asset.alpha += 1 / 24;
        if (asset.alpha >= 1)
        {
          asset.alpha = 1;
          setTimeout(function()
          {
            let fadeOut = setInterval(function()
            {
              asset.alpha -= 1 / 24;
              if (asset.alpha <= 0)
              {
                asset.alpha = 0;
                stage.removeChild(asset);
                clearInterval(fadeOut);
              }
            }, 1000 / 24)
          }, 1000 * duration)
          clearInterval(fadeInOut);
        }
      }, 1000 / 24)
    }

我调用这个函数的方式是这样的:

    fadeInOut(assets.eiko, 2, stage);
    fadeInOut(assets.logo, 3, stage);

我真的不明白为什么第二次调用该函数是运行与第一次同时调用。

希望你能帮助我,因为这对我来说是一个非常重要的项目。

提前致谢。

恕我直言,你需要这样的东西,我做了两个例子:)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script>
function init() 
{
    var stage = new createjs.Stage("canvas");
    createjs.Ticker.setFPS(24);  //set some FPS
    createjs.Ticker.addEventListener("tick", stage); //set autiomatic refresh

    //draw some circles for the example usage
    var circle1 = new createjs.Shape();
    circle1.graphics.beginFill("#FF0000").drawCircle(0,0,50);
    circle1.x=100;
    circle1.y=100;
    circle1.alpha=0;
    stage.addChild(circle1);

    var circle2 = new createjs.Shape();
    circle2.graphics.beginFill("#0000FF").drawCircle(0,0,50);
    circle2.x=300;
    circle2.y=100;
    circle2.alpha=0;
    stage.addChild(circle2);

    //first version with function call after the first animation
    createjs.Tween.get(circle1).to({alpha:1},1000).to({alpha:0},1000).call(
        function ()
        {
            createjs.Tween.get(circle2).to({alpha:1},1000).to({alpha:0},1000)
        }
    ); 

    //seconds version: with delay instead of onComplete function, comment first version above, uncomment code below and try
    /*
    createjs.Tween.get(circle1).to({alpha:1},1000).to({alpha:0},1000);
    createjs.Tween.get(circle2).wait(2000).to({alpha:1},1000).to({alpha:0},1000)
    */


}
</script>
</head>
<body onload="init();">
    <canvas id="canvas" width="600" height="400"></canvas>
</body>
</html>