在Javascript中调用多个延迟的最有效方法是什么?

时间:2015-01-30 21:26:35

标签: javascript html css

我正在加载一个网页,我希望每个元素都可以加入"淡入"影响。我有动画工作,我可以得到一个元素,但是,在我的第一个setTimeout行之后,其余部分似乎无法执行。

    function runAnimation() {
document.getElementById("object1").style.WebkitAnimation = "fadein 1.7s"; //Animation line 1
setTimeout(donothing(), 5000); //wait 5 seconds
document.getElementById("object2").style.WebkitAnimation = "fadein 1.7s"; //Animation line 2
}

我的问题是,第二个动画线(以及它之后的任何动画)都没有运行。我已经在不同的ID上尝试了其他样式项,它似乎在setTimeout之后没有执行任何操作(这是正常的吗?)那么处理多个延迟的最佳方法是什么?因为我还需要在以后添加一些对象。

1 个答案:

答案 0 :(得分:1)

它什么也不做的原因是因为Javascript没有同步执行setTimeout回调。它将通过将其添加到事件循环中异步执行它,然后在等待执行回调时继续执行下一个命令。您需要将第二个动画传递给超时,而不是donothing()

  function runAnimation() { 
     // Do your first step
     document.getElementById("object1").style.WebkitAnimation = "fadein 1.7s";

     //Then pass a function to setTimeout that will execute your second step
     setTimeout(function(){
     document.getElementById("object2").style.WebkitAnimation = "fadein 1.7s"; 
     }, 5000); //wait 5 seconds
}

MDN - WindowTimers.setTimeout()

关于setTimeout如何使用异步回调来“中断”执行流程的基本示例。

   // this first console call will be executed immediately
console.log('I will execute immediately!');

// this function will be scheduled to execute after 2 seconds. 
// Even though its defined second, it will execute last!

setTimeout(function(){
  console.log('Ill execute last, event though Im defined second!')
 }, 2000)

// Javascript will just continue forward, making a note that in 
// 2 seconds it has to execute that ^ function. 
// That means this next call will come next despite the 
// previous function not being executed yet.
console.log('Ill come second!');