循环Javascript计时器

Looping Javascript timer

本文关键字:计时器 Javascript 循环      更新时间:2023-09-26

我正在尝试运行顺序倒计时计时器,但不知道如何等待计时器完成后再移动到下一个项目。

for(var i = 0; i < 5; i++)
{
    var count = 5;
    var counter = setInterval(timer, 1000);
}
function timer()
{
    count--;
    if (count <= 0)
    {
        $('.workout-timer').text(count + "secs");
        clearInterval(counter);
        return;
    }
    $('.workout-timer').text(count + "secs");
}

这只是进入负数,但是没有for循环,代码从5计数到0就可以了。所以我的问题是如何一个接一个地得到几个倒计时?计时器不是正确的方法吗?

你可以这样做:

function startCountdown(count, delay, callback) {
    if (!count) {
        callback && callback();
        return;
    }
    //do something here
    console.log(count);
    setTimeout(function () {
        startCountdown(--count, delay, callback);
    }, delay);
}
startCountdown(5, 1000, function () {
    startCountdown(5, 1500);
});

然而,如果你有很多嵌套的回调,这可能会变得很混乱,但是这里有一个方法可以用来处理这个问题:

var queue = [
        { count: 5, delay: 1000 },
        { count: 10, delay: 200 },
        { count: 5, delay: 5000 }
    ];
processNextCountdown();
function processNextCountdown() {
    var options = queue.shift();
    if (options) {
        startCountdown(options.count, options.delay, processNextCountdown);
    }
}

间隔就像会重新安排自己的超时(这与开始新超时的超时不同)。因为时间间隔会重新安排自己,所以只创建一个。(或者,只在真正需要的时候使用)

原始帖子的问题是它正在创建5间隔(因为它们是在循环中创建的),然后只保留最后创建的间隔ID(在counter中)!因此,clearInterval只停止最后一个间隔,其他4个间隔继续运行,运行,运行。

下面是一些带注释的代码,没有原来的问题:

var count = 5;
// only need ONE interval
var counter = setInterval(timer, 1000);
// so we do one count RIGHT NOW
timer();
function timer() {
  // display first, so we start at 5: 5, 4 .. 1
  console.log(count);
  count--;
  if (count < 0) {
    // to repeat the count, comment out the clearInterval
    // and do `count = 5;` or similar .. take it from here :D
    clearInterval(counter);
  }
}

要为每个倒计时创建单独的"state",要么创建一个新的倒计时对象,在属性中维护state,要么使用闭包。下面是一个使用闭包的示例。我还添加了对回调函数的支持,以展示如何使这样的函数更通用:

function makeCountdown(startCount, delay, fn) {
    fn = fn || function (i) {
       // default action, if fn not specified
       console.log(i);
    };
    // local variables
    var count = startCount;
    var counter = setInterval(timer, delay);
    timer();
    function timer() {
        // now count and counter refer to variables in the closure (keyword!)
        // which are different each time makeCountdown is called.
        fn(count);
        count--;
        if (count < 0) {
            clearInterval(counter);
        }
    }
}
makeCountdown(20, 500); // uses default function
makeCountdown(10, 1000, function (i) { console.log(10 - i) });
makeCountdown(5, 2000, function (i) { console.log("SLOW! " + i) });

练习:

  1. 为倒计时"完成"添加回调函数,以便倒计时可以串联运行。
  2. 消耗一个串联发生器并使用它来生成下一个count值。
  3. makeCountdown返回一个可以用来控制倒计时的对象
  4. 玩得开心!