JavaScript-延迟一组setTimeout活动

JavaScript - delay a set of setTimeout activities

本文关键字:一组 setTimeout 活动 延迟 JavaScript-      更新时间:2023-09-26

我有一组对象要使用JavaScript中的setTimeout()函数在不同时间显示。我所做的是运行一个循环,为每个元素初始化一个setTimeout事件。

我用来为每个元素设置Timeout的代码:

for (i = currentIndex; i < this.items.length; i++) {
    var object = "element#"+i;
    var delay = 10*i;
    this.keepDelay[id] = new Timer(function() {
                                $("#objectSet").css("display", "none").html(object).fadeIn("fast");
                                currentIndex = id;
                            }, delay);
}

Timer类是

function Timer(callback, delay) {
    var timerId, start, remaining = delay;
    // works
    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };
    // works    
    this.resume = function() {
        start = new Date();
        id = currentIndex;
        timerId = window.setTimeout(callback, remaining);
    };
    // does NOT work
    this.speedup = function() {
        remaining -= 100;
        window.clearTimeout(timerId);
        timerId = window.setTimeout(callback, remaining);
    }
    // does NOT work
    this.slowdown = function() {
        remaining += 100;
        window.clearTimeout(timerId);
        timerId = window.setTimeout(callback, remaining);
    }
    this.resume();
}

resume()pause()方法确实有效。CCD_ 3尝试根据延迟值一个接一个地显示每个对象。pause()是不言自明的。这两个工作得很好。

现在我想加快和减缓对象的延迟,我试着写speedup()和slowdown()方法,但不知何故它们不起作用。

看着代码,我不知道为什么它不会,也许我已经专注于它太久了,所以我需要从新的思维中寻求帮助。

您需要计算已经过去的时间,以便计算出设置新计时器的时间。以下是.speedup():的示例

this.speedup = function() {
    window.clearTimeout(timerId);
    var elapsed = new Date() - start;
    remaining-= elapsed + 100;
    if (remaining > 0) {
        this.resume();
    } else {
        callback();
    }
}

您可以对.slowdown()执行类似的操作。


我突然想到,这可以做得简单一点:

this.speedup = function() {
    this.pause();
    remaining-= 100;
    this.resume();
}
this.slowdown = function() {
    this.pause();
    remaining+= 100;
    this.resume();
}

然后,将this.resume()更改为这个,以确保remaining不会变为负:

this.resume = function() {
    start = new Date();
    id = currentIndex;
    if (remaining > 0) {
        timerId = window.setTimeout(callback, remaining);
    } else {
        callback();
    }
};