首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环遍历字符串数组,每次循环之间有任意时间间隔(JS)

循环遍历字符串数组,每次循环之间有任意时间间隔(JS)
EN

Stack Overflow用户
提问于 2019-03-24 18:09:18
回答 4查看 58关注 0票数 0

我想创建一个字符串反复循环的动画,每次一个字符。我的字符串中有两个数组:

代码语言:javascript
复制
let stringArray = ['TestOne', 'TestTwo'];

我想重复遍历这个数组(string,一个-> string,两个-> back to string,一个-> string,两个-> ...连续)。我想打印字符串中的字符,一次打印一个字符。打印完所有字符后,我将清除打印的字符串,并继续处理字符串2的字符。插图:

代码语言:javascript
复制
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。我怎样才能做到这一点呢?

EN

Stack Overflow用户

回答已采纳

发布于 2019-03-24 18:28:28

好吧,只要人们在发布解决方案,我就会发布显而易见、简单的解决方案,参见评论:

代码语言:javascript
复制
{ // 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);
}

这部分:

代码语言:javascript
复制
arrayIndex = (arrayIndex + 1) % stringArray.length;

当你有一个索引(0...n-1)并想要递增它并循环时,这是一个很方便的技巧。假设您有3个条目,因此索引为0、1和2。当索引为2时,(2 + 1)33 % 30,因此它会回绕。

票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55322669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档