Javascript - 循环中最后一次超时后调用函数

时间:2017-04-19 23:08:17

标签: javascript function loops reactjs timeout

我目前有一个循环,每秒动画HTML元素,在最后一个动画完成后,我想接受用户输入:

playSequence(currentLevel) {
  console.log("playing level " + currentLevel)
  for (var q = 0; q < currentLevel; q++) {
    (function(q) {
      setTimeout(function() {
        var active = '#' + sequence[q].toString(); //the div currently being animated
        console.log(active);
        var currentColor = $(active).css('background-color');
        var newColor = currentColor.replace("0.6", "1.0");

        $(active).animate({
          backgroundColor: newColor
        }, 100, function() {}).delay(900).animate({
        backgroundColor: currentColor
        }, 100, function() {
        if (q === (currentLevel - 1)) {
          console.log("done"); //this runs
          this.getInput(1, currentLevel); //this does not
        }
      });

     }, 1000 * q)
   }(q));
 }    
}

在最后一个动画之后,会打印“done”,但不会调用getInput,因为函数开头的console.log不会打印。

为什么它不会在最后一个计时器完成后运行,即使它上面的console.log呢?

但是,如果我像这样移动getInput,

playSequence(currentLevel) {
  console.log("playing level " + currentLevel)
  for (var q = 0; q < currentLevel; q++) {
    (function(q) {
      setTimeout(function() {
        var active = '#' + sequence[q].toString(); //the div currently being animated
        console.log(active);
        var currentColor = $(active).css('background-color');
        var newColor = currentColor.replace("0.6", "1.0");

        $(active).animate({
          backgroundColor: newColor
        }, 100, function() {}).delay(900).animate({
        backgroundColor: currentColor
        }, 100, function() {
        if (q === (currentLevel - 1)) {
          console.log("done"); //this runs

        }
      });

     }, 1000 * q)
   }(q));
 }
this.getInput(1, currentLevel); //this runs   
}

然后getInput会运行,但它不能正常运行,因为它在动画完成之前运行,因为它在timeOut范围之外运行。

注意:这包含在React类中,而getInput不是playSequence中的方法,它们都在一个名为“Game”的类中

1 个答案:

答案 0 :(得分:0)

@ PHPGlue的评论有效,留下他们的答案以防将来有人偶然发现:

  

如果你做var t = this;在你的所有匿名函数之上,你可以在那里使用t.getInput()