简体   繁体   中英

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. 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.

JS Snippet

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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