【问题标题】:JavaScript, Execute function after functionJavaScript,函数后执行函数
【发布时间】:2017-10-22 22:54:12
【问题描述】:
mainFunc(){
 firstFunc();
 SecondFunc();
 Playball();
}


function Playball () {

var paper = new Raphael(0, 0, 800, 500);
var backGround = paper.rect(0, 0, 800, 500);

var ball = paper.circle(400, 0, 30);
ball.attr({fill: "blue"});

function step1() {
    ball.animate({cx: 400, cy: 600}, 2500);
}

step1();
};

这是我到目前为止写的,我还有更多的功能需要连续执行。我知道我可以使用一个简单的回调函数,但我无法让它工作,Step2 永远不会执行。以下是我尝试过的。鉴于我有多种功能,在这种情况下我还可以使用更好的方法吗?我无法使用 SetTimeout,因为我的主要功能是在点击事件上触发的。

function Playball (callback) {

var paper = new Raphael(0, 0, 800, 500);
var backGround = paper.rect(0, 0, 800, 500);

var ball = paper.circle(400, 0, 30);
ball.attr({fill: "blue"});

function step1() {
    ball.animate({cx: 400, cy: 600}, 2500);
}

step1();
return true;
};

Playball(step2());

【问题讨论】:

  • Playball(); step2() 应该更适合您。我看不出有什么理由在这里使用回调?
  • 您遇到了什么问题?
  • 我试过了,但是 step2 没有执行。

标签: javascript methods callback


【解决方案1】:

我假设您希望 step2 在 step1 的动画之后开始,那么这样可以吗?

function Playball (callback) {

  var paper = new Raphael(0, 0, 800, 500);
  var backGround = paper.rect(0, 0, 800, 500);

  var ball = paper.circle(400, 0, 30);
  ball.attr({fill: "blue"});
  //http://dmitrybaranovskiy.github.io/raphael/reference.html#Element.animate
  function step1() {
    ball.animate(
      {cx: 400, cy: 600}//params
      , 2500            //number of milliseconds for animation to run
      ,undefined        //easing type
      ,callback         //callback function. Will be called at the end of animation
    );
  }

  step1();
  return true;
};

Playball(step2);

可以在here找到一个示例小提琴。

【讨论】: