【问题标题】:How to call a function after all setTimeout functions is done完成所有 setTimeout 函数后如何调用函数
【发布时间】:2017-05-21 00:09:27
【问题描述】:

前面所有函数都完成后如何调用第二个函数。

function first() {
    // code here
    setTimeout( function() {
        // code here
    }, 1000);

    // code here
    setTimeout( function() {
        // code here
    }, 3000);

    // code here
    setTimeout( function() {
        // code here
    }, 3800);
}

function second() {
    // code here
}

first();
first();
second();
first();
second();

似乎所有功能都在同一时间执行。
非常感谢。

【问题讨论】:

  • 基本上每次调用都需要增加超时时间(毫秒),否则都是同时触发的。
  • 调用 settimeouts 是异步的。他们不会互相等待
  • 根据条件调用的函数,所以不知道需要的超时时间。
  • 如果你需要在first异步方法之后运行second函数,你可以将first包装在一个promise中,并在promise解决时在then链中调用second

标签: javascript jquery settimeout


【解决方案1】:

如果您需要在上次超时后调用特定函数,我认为这将为您指明正确的方向。当然,它可以写得更好,带有可重用的“类”等。

function myTimeout(f,t) {
    var p = new Promise(resolve=>{
      setTimeout(()=>{
        resolve(f.apply(this,[]));
    }, t);
    });
    

    //return p.promise(); 
  return p;
}

function first() {
    var numberOfTimeouts = 3
    // code here
    myTimeout(()=>{
        // code here
        console.log('a')
    }, 1000).then(()=>{
      numberOfTimeouts--;
      if (!numberOfTimeouts) second()
    });

    // code here
    myTimeout( function() {
        console.log('b')
    }, 3000).then(()=>{
      numberOfTimeouts--;
      if (!numberOfTimeouts) second()
    });

    // code here
    myTimeout( function() {
       console.log('c')
    }, 3800).then(()=>{
      numberOfTimeouts--;
      if (!numberOfTimeouts) second()
    });
}

function second() {
   console.log('d')
}

first();

【讨论】:

  • 如果你打算使用 Promises,至少使用 Promise.all 来同步它们,而不是使用笨拙的计数器
猜你喜欢
  • 2015-08-05
  • 2017-01-10
  • 2019-04-21
  • 1970-01-01
  • 2019-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-30
相关资源
最近更新 更多