简体   繁体   English

如何延迟每个循环迭代以创建顺序效果?

[英]How to delay each loop iteration to create sequential effect?

Is it possible to add a delay inside a forEach so you can see a slight delay as each span innerHTML is swapped out in order. 是否可以在forEach内部添加延迟,以便在将每个span innerHTML HTML按顺序交换出来时看到轻微的延迟。 At the moment my loop happens, the relative span gets injected but the loop is that quick that all the letters appear at the same time. 在我的循环发生的那一刻,相对跨度被注入,但是循环如此之快,以至于所有字母同时出现。 Would be nice to delay each inject by 200ms if possible, I'm just drawing a blank on how to do this. 如果可能的话,最好将每次注入延迟200毫秒,我只是在做一个空白上做一下。

JS Snippet JS代码段

function showCity() {
    newStringArr = cities[i].split('');

    var tickerSpans = ticker.children;      
    newStringArr.forEach(function(letter, idx) {

        // Delay each assignment by 200ms?
        tickerSpans[idx].innerHTML = letter;

    });

    i++;

    if(i <= 2) {
        setTimeout(function() {
            randomWordInterval = setInterval(randomiser, SPEED, false);
        }, PAUSE);
    }
}

Code link http://codepen.io/styler/pen/jPPRyy?editors=001 代码链接http://codepen.io/styler/pen/jPPRyy?editors=001

You can always create a function that just continues to call itself until it reaches the end of the array use recursion: 您可以始终 创建一个继续调用自身的函数,直到到达数组末尾为止 使用递归:

function createHtml(array, index, elems) {
    elems[index].innerHTML = array[index++];
    if ((index + 1) <= array.length) {
        setTimeout(function() {
            createHtml(array, index, elems);
        }, 200);
    }
}

var newStringArr = cities[i].split('');
var tickerSpans = ticker.children;

createHtml(newStringArr, 0, tickerSpans);

Working demo: http://codepen.io/anon/pen/PqPjqe 工作演示: http : //codepen.io/anon/pen/PqPjqe

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

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