执行一系列的$timeout

Executing a series of $timeouts

本文关键字:timeout 一系列 执行      更新时间:2023-09-26

我正在做一个AngularJS应用程序。该应用程序需要交替超时。这种交替由数组处理。这个数组看起来像这样:[3000, 1000, 3000, 1000, 5000] .

这个数组表示运行一个操作三秒钟。然后,等一秒钟。然后运行另一个操作三秒钟。然后再等一秒钟。最后,运行另一个操作5秒钟。操作将有所不同。无论哪种方式,我都不确定如何按顺序执行它们。

如何在AngularJS中执行一系列$timeout元素?

谢谢!

这听起来更像是自定义计时器,因为您需要跟踪时间,而不仅仅是延迟操作。

无论如何,您需要在每个操作的运行和暂停时间中格式化数据。像这样:

var operations = [{fun: oneFunction, wait: 1000, run: 3000}, {fun: twoFunction, wait: 2000, run: 5000];

然后你需要处理这些函数,在它们各自的时间内运行它们:

function handleOperations(operationArray) {
    for (var i = 0; i < operationArray.length; i++) {
         var start = Date.now();
         if ((Date.now()-start) <= operationArray[i].run) {
             operationArray[i].fun(); //run while the timer is still going
         } else {
             //otherwise, wait for specified time
             var waitStart = Date.now();
             if ((Date.now()-waitStart) <= operationArray[i].wait) {};
         }
    }
}