我有一个单词(文本)数组,我想将其逐一附加到目标 div,并在附加每个单词后有一小段延迟。我目前可以使用下面的代码来做到这一点。
var showText = function (target, text, index, interval) {
if (index < text.length) {
$(target).append(text[index++]);
setTimeout(function () { showText(target, text, index, interval); }, interval);
}
}
但是,我还希望脚本在附加数组中的最后一个单词后再次转到数组的开头,并继续将单词附加到目标以进行新的循环。我想定义该过程将运行的周期数。
我认为嵌套循环将是如下的解决方案
(function () {
for (i = 0; i < 3; i++) {
(function myloop (i) {
setTimeout(function () {
$(target).append(text[i]);
if (i > 0) {
myLoop(i);
}
}, 1000);
})(10);
}
})
但由于某种原因,这是将数组的每个字重复 3 次,而不是循环数组 3 次。我想我对如何在这个循环中使用 JS 感到困惑。你能帮我解决这个问题吗?
最佳答案
如之前所述,请使用 %
运算符,并仅更新 Max Limit 的 if
条件。
示例
function appendWords(arr, index, maxRepeat) {
if (++index >= arr.length * maxRepeat) return;
var word = arr[(index % arr.length)];
document.querySelector('.content').innerHTML += " " + word;
initTimeout(arr, index, maxRepeat)
}
function initTimeout(arr, index, max) {
setTimeout(function() {
appendWords(arr, index, max)
}, 1000)
}
function main() {
var arr = ['test', 'foo', 'world', 'bar'];
var index = -1;
initTimeout(arr, index, 2)
}
main();
<div class="content"></div>
关于javascript - 将项目逐一添加到数组中,有延迟,并在所有项目都用完时重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40993040/