我想创建一个字符串反复循环的动画,每次一个字符。我的字符串中有两个数组:
let stringArray = ['TestOne', 'TestTwo'];
我想重复遍历这个数组(string,一个-> string,两个-> back to string,一个-> string,两个-> ...连续)。我想打印字符串中的字符,一次打印一个字符。打印完所有字符后,我将清除打印的字符串,并继续处理字符串2的字符。插图:
T
Te (250 ms after the first char)
Tes (250 ms after the second char)
Test (All characters are printed 250ms after the previous char)
TestO
TestOn
TestOne
T
Te
Tes
Test
TestT
TestTw
TestTwo
... (continue with TestOne again)问题是,我希望每个字符在之前打印的字符之后只打印250ms。我怎样才能做到这一点呢?
发布于 2019-03-24 18:28:28
好吧,只要人们在发布解决方案,我就会发布显而易见、简单的解决方案,参见评论:
{ // A scoping block so the variables aren't globals
// (unnecessary if you're using modules)
let stringArray = ['TestOne', 'TestTwo'];
let arrayIndex = 0;
let stringIndex = 1;
// Start a timer that will call the callback every 250ms (or so)
setInterval(() => {
// Get the relevant string
const str = stringArray[arrayIndex];
// Output the substring
console.log(str.substring(0, stringIndex));
// Move to the next character
++stringIndex;
// Need to move to next string?
if (stringIndex > str.length) {
// Yes, go back to the beginning of the string and
// move to the next entry in the array, wrapping
// around if we reach the end
stringIndex = 1;
arrayIndex = (arrayIndex + 1) % stringArray.length;
}
}, 250);
}
这部分:
arrayIndex = (arrayIndex + 1) % stringArray.length;当你有一个索引(0...n-1)并想要递增它并循环时,这是一个很方便的技巧。假设您有3个条目,因此索引为0、1和2。当索引为2时,(2 + 1)为3,3 % 3为0,因此它会回绕。
https://stackoverflow.com/questions/55322669
复制相似问题