简体   繁体   English

如何在 JavaScript 中重新启动 forEach() 循环

[英]How to restart a forEach() loop in JavaScript

I have the following loop which goes through the characters of each array element, and stops.我有以下循环遍历每个数组元素的字符并停止。

var container = $("#myid")
container.shuffleNames();
const names = ["", "john", "rita", "katsigaros", "jonathan", "peepee"];

names.forEach((i, t) => {
        (function(index, text) {
            setTimeout(function(){
                container.shuffleNames({
                    "text": text
                });
            }, index * 3000);
        })(t, i);
});

How can I make it to kick back from the beginning when looping ends and restart for infinity?当循环结束并重新开始无限时,我怎样才能让它从头开始?

You can use an interval that runs forever and just access the next element in names each time, bu incrementing a variable that stores the index of the current name and using % to reset it back to 0 when it exceeds the length of the array:您可以使用一个永远运行的间隔,每次只访问names中的下一个元素,增加一个存储当前名称索引的变量,并在超过数组长度时使用%将其重置回 0:

let index = 0;
setInterval( ( ) => {
  container.shuffleNames({
    "text": names[ index = (index + 1) % names.length ]
  });
}, 3000 );

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

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