1

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

3
  • 2
    You'd have to do something like first loop through make it setTimeout to run in 200ms, second set it to 400ms, 3rd 600ms, etc. JavaScript is essentially single threaded. There is no "sleep" method. Of course that wouldn't be 100% accurate, since the second one might need to really be 399.9ms, not 400ms because some time has been taken between each loop iteration. If you're animating 10 chars, it won't be noticeable. If you're animating 10 million chars, it will be. Commented May 5, 2015 at 19:03
  • So wrap the innerHTML assignment in a setTimeout, use the idx * setTimeout duration. Something like that? Commented May 5, 2015 at 19:08
  • Yes, EXCEPT, make sure you're careful because of closures. You should pass the letter variable and idx to a function that calls setTimeout. Otherwise you'll quickly discover that no animation happens because every iteration will receive the "last" value of letter due to the fact that the function runs asynchronously :) Commented May 5, 2015 at 19:11

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.