gpt4 book ai didi

JavaScript - 延迟一组 setTimeout 事件

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:25:33 24 4
gpt4 key购买 nike

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

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

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() 方法确实有效。 resume() 尝试根据延迟值一个接一个地显示每个对象。 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();
}
};

关于JavaScript - 延迟一组 setTimeout 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26355705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com