Angular 4 setTimeout()具有可变的延迟和等待

Cri*_*ina 6 javascript typescript angular

我有与的活动清单timestamp。我想要的是基于显示事件timestamp:

要添加延迟:

delay = timestamp(t+1) - timstamp(t)
Run Code Online (Sandbox Code Playgroud)

我知道这不适用于setTimeout,但是有一种解决方法,如果超时是恒定的,就我而言不是。

是否可以让下一个setTimeout()等待上一个?具体来说,如果第setTimeout()一个延迟5秒,第二个延迟3秒,则第二个将首先出现。我希望它们的顺序相同,但要一个接一个地执行。

此示例适用于恒定延迟,但是我想根据对列表进行迭代所获得的信息来计算延迟。

for (i = 1; i <= 5; ++i) {
  setDelay(i);
}

function setDelay(i) {
  setTimeout(function(){
    console.log(i);
  }, 1000);
}
Run Code Online (Sandbox Code Playgroud)

Roh*_*rma 9

您可以改用IIFE(立即调用函数表达式)和函数递归。喜欢:

let i = 0;
(function repeat(times){
  if (++i > 5) return;
  setTimeout(function(){
    console.log("Iteration: " + i);
    repeat();
  }, 5000);
})();
Run Code Online (Sandbox Code Playgroud)

在这里演奏小提琴。


use*_*994 5

不要在循环内调用它,因为它不会等待setTimeout完成。

您可以传递一个您想要等待的时间列表,并递归地迭代它们:

let waits = [5000, 3000, 1000];

function setDelay(times) {
  if (times.length > 0) {
    // Remove the first time from the array
    let wait = times.shift();
    console.log("Waiting", wait);
    
    // Wait for the given amount of time
    setTimeout(() => {
        console.log("Waited ", wait);
        // Call the setDelay function again with the remaining times
        setDelay(times);
    }, wait);
  }
}

setDelay(waits);
Run Code Online (Sandbox Code Playgroud)


nip*_*777 5

当使用最新的 Typescript 或 ES 代码时,我们可以为此使用 aync/await。

let timestampDiffs = [3, 2, 4];

(async () => {
  for (let item of timestampDiffs) {
    await timeout(item * 1000);
    console.log('waited: ' + item);
  }
})();

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
Run Code Online (Sandbox Code Playgroud)

我们需要将 for 循环包装在一个异步立即调用的函数中,因为要支持 await。

我们还需要一个超时函数,一旦超时完成就返回一个承诺。

之后,我们在继续循环之前等待超时完成。