我有以下代码:

function newGraphic() {
  $.post('./lexiconGraph.pl', {
    'tag' : this.getAttribute('apolo'),
    'apoloKey' : this.id,
    'h' : surface.h,
    'w' : surface.w,
    'operation' : 'newGraphic'
  }, function(result) {
    minGraphic();
    // STOP AND WAIT //
    document.getElementById('container').innerHTML = result;
    getNodes();
    // STOP AND WAIT //
    maxGraphic();
  });
}

function minGraphic() {
  if (z > 0.01) {
    zoom(parseFloat(z - 0.01));
    setTimeout('minGraphic();', 5);
  }
}


问题是:函数minGraphic创建未知持续时间的“动画效果”(取决于图形的大小)。我需要找到一种方法,使仅当minGraphic函数完成时才执行以下几行。
有谁知道我该怎么做?

注意:将以下行放入minGraphic函数中是不可选项,因为我已经在其他地方使用了此函数。

最佳答案

动画完成时使用回调。像这样:

function newGraphic() {
  $.post('./lexiconGraph.pl', {
    'tag' : this.getAttribute('apolo'),
    'apoloKey' : this.id,
    'h' : surface.h,
    'w' : surface.w,
    'operation' : 'newGraphic'
  }, function(result) {
    var afterAnimation = function()
    {
      document.getElementById('container').innerHTML = result;
      getNodes();
      maxGraphic();
    };

    minGraphic(afterAnimation);
  });
}

function minGraphic(cb) {
  if (z > 0.01) {
    zoom(parseFloat(z - 0.01));
    setTimeout(function() { minGraphic(cb); }, 5);
  }
  else
  {
    if(cb) cb();
  }
}


如果我正确遵循的话,这将触发miniGraphic的启动,并将回调传递给动画完成后将执行的函数(即z不大于0.01)。当该事件发生时,如果传入了回调(cb),它将调用该函数,从而触发动画的下一步。

如果您有东西需要等待maxGraphic方法,则可以采用相同的概念。

另外,如果您可以使用jQuery,则jQuery具有内置的动画后回调方法,供您使用。 See this documentation

关于javascript - setTimeout()回调完成后执行JS代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18983265/

10-11 13:02
查看更多