简体   繁体   English

在每个循环(JS)之间以任意时间循环遍历字符串数组

[英]Looping over an array of strings with an arbitrary time between each loop (JS)

I want to create an animation of strings being looped over and over again one character at a time. 我想创建一个字符串动画,一次一次又一次地循环。 I have two arrays in my string: 我的字符串中有两个数组:

 let stringArray = ['TestOne', 'TestTwo']; 

I want to loop over said array repeatedly (string one -> string two -> back to string one -> string two -> ... continuously). 我想反复遍历所述数组(字符串一->字符串二->返回字符串一->字符串二-> ...连续)。 I want to print the characters of string one one character at a time. 我想一次打印一个字符串一个字符。 After print all its characters, I will clear the printed string and proceed with the character of string two. 在打印完所有字符后,我将清除打印的字符串并继续使用字符串2的字符。 Illustration: 插图:

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)

The problem is, I want each character to be printed only 250ms after a previously printed character. 问题是,我希望每个字符仅在先前打印的字符之后250毫秒被打印。 How can I achieve this? 我该如何实现?

You could take an array with the indices and an interval for the display. 您可以使用带有indices和显示间隔的数组。

The array indices contaisn two values at start, [0, 0] which means the first item of stringArray and from this string the first character. 数组indices在开头包含两个值, [0, 0] ,这意味着stringArray的第一项,从该字符串开始的第一个字符。

For every loopm, the caracter index gets an increment and this value is checked against the lenght of the string. 对于每个循环,字符索引都会增加,并根据字符串的长度检查此值。 If greater, then the index of the string gets an increment and the string index is resetted to zero. 如果更大,则字符串的索引将递增,并将字符串索引重置为零。

To prevent the string index is greater than the actual count of strings, the value is resetted by taking a remainder assignment. 为防止字符串索引大于字符串的实际计数,可通过进行余数分配来重置该值。

The pattern 模式

(indices => () => {
    // ...
})([0, 0])

is an IIFE ( immediately-invoked function expression ), which takes the array as value for the first parameter. 是IIFE( 立即调用的函数表达式 ),它将数组作为第一个参数的值。 It is a closure over the array and allows to use the resturnd function as callback for the interval. 它是数组的闭包,允许将返回的函数用作该时间间隔的回调。

Tha advantage is to have a data set which is not changable from the outside and is avilable for any call of the callback. 这样做的好处是拥有一个数据集,该数据集不能从外部更改,并且可用于任何回调调用。

 let stringArray = ['TestOne', 'TestTwo']; setInterval((indices => () => { document.getElementById('out').innerHTML = stringArray[indices[0]].slice(0, indices[1]); indices[1]++; if (indices[1] > stringArray[indices[0]].length) { indices[0]++; indices[1] = 0; } indices[0] %= stringArray.length; })([0, 0]), 250) 
 <pre id="out"></pre> 

Well, as long as people are posting solutions, I'll post the obvious, simple one, see comments: 好吧,只要人们发布解决方案,我都会发布显而易见的,简单的解决方案,请参阅评论:

 { // 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); } 

This part: 这部分:

arrayIndex = (arrayIndex + 1) % stringArray.length;

is a handy trick for when you have an index (0...n-1) and want to increment it and loop around. 当您有一个索引(0 ... n-1)并想增加它并循环时,这是一个方便的技巧。 Say you have 3 entries, so the indexes are 0, 1, and 2. When you're at 2, (2 + 1) is 3 and 3 % 3 is 0 , so it wraps around. 假设您有3个条目,因此索引分别为0、1和2。当您位于2时, (2 + 1)33 % 30 ,所以它会回绕。

One way you could do this is without using a loop, but instead using a function which takes some parameters so you know how far or long you are in a word, and which word you are currently printing in your array. 您可以执行此操作的一种方法是不使用循环,而是使用带有一些参数的函数,这样您就可以知道单词中的距离或长度,以及当前正在数组中打印的单词。

Once you are printing with a function, simply add a setTimeout() in the function and then you can control the delay. 使用函数打印后,只需在函数中添加setTimeout()即可控制延迟。 See https://www.w3schools.com/jsref/met_win_settimeout.asp for more info on timeouts in javascript. 有关JavaScript超时的更多信息,请参见https://www.w3schools.com/jsref/met_win_settimeout.asp

 strings = []; for (var i = 1; i <= "TestOne".length; i++) strings.push ("TestOne".substring (0, i)); for (var i = 1; i <= "TestTwo".length; i++) strings.push ("TestTwo".substring (0, i)); var position = 0; setInterval (() => { console.log (strings [position++]); if (position == strings.length) position = 0; }, 250); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM