gpt4 book ai didi

javascript - 在 Javascript setInterval 函数中动态修改速度

转载 作者:行者123 更新时间:2023-11-29 16:30:45 25 4
gpt4 key购买 nike

我有一个 react 应用程序,需要显示一些句子之间具有不同间隔的文本,一次一个。

所以我所做的就是将所有句子放入一个数组中并创建一个 setInterval 函数:

  startShowingText() {
let i = 0

this.setState({
timer: window.setInterval(() => {
this.setState({
sentence: SENTENCES[i]
})

i += 1
}, this.state.startingDuration)
})
}

不幸的是,这种方法有很多缺点:

1) 需要检查才能终止;

2)我无法动态修改时间,因此一旦设置了 this.state.startingDuration,这将是所有句子的速度...

3) 由于某些原因,如果我将 window.setInterval 函数分配给状态之外的变量,则不会执行该代码段:

  startShowingText() {
let i = 0
console.log('here')
const timer = window.setInterval(() => {
this.setState({
sentence: SENTENCES[i]
})

i += 1
}, this.state.startingDuration)
console.log('there')
}

这段代码只是打印:

here

there

不触发实际计时器。

如何改进代码并使间隔动态可调?

最佳答案

您可以使用的一种方法是从游戏开发世界借用的,他们创建以特定时间间隔运行的“游戏循环”。在循环中,您可以根据当前循环迭代来确定是否到了输出该句子的时间。

一个粗略的例子:

const sentences = {
"My first sentence.": 1,
"My second sentence.": 20,
"My third sentence.": 25,
"My fourth sentence.": 40
};
const ticks = 100;
const maxLoops = 100;

const i = setInterval(writeLoop, ticks);

let loopCounter = 0;
function writeLoop() {

if (loopCounter > maxLoops) {
clearInterval(i);
}

for (sentence in sentences) {
let targetLoop = sentences[sentence];
if (loopCounter == targetLoop) {
document.write('<div>'+sentence+'</div>');
}
}

loopCounter = loopCounter + 1;
}

关于javascript - 在 Javascript setInterval 函数中动态修改速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524394/

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