Danny Peck Danny Peck - 2 months ago 8
Javascript Question

Using setTimeout in a Loop

function showColors() {
$.each(colorList, function(value) {
setTimeout(function(){
revealColor(colorList[value]);
}, 1000);
});
}


I'm basically trying to set things up here so the revealColor function runs every 1000 milliseconds until I hit the end of the entire colorList array. Unfortunately, it queues up all the setTimeout events instantly and then 1000 milliseconds later, the revealColor function runs once for every value in the array.

I'm sure there's an easier way to do this that I'm just not seeing. Any help would be great!

Answer

Using pure JS:

var colorList = ["red", "green", "blue"];

var colorIndex = 0;

var handler = setInterval(function() {
    revealColor(colorList[colorIndex]);
    colorIndex++;
    if (colorIndex >= colorList.length) {
        clearInterval(handler);
    }
}, 1000);

function revealColor(color) {
    document.body.style.background = color;
}

Using jQuery:

var colorList = ["red", "green", "blue"];

var delay = 1000;

$.each(colorList, function (value) {
    setTimeout(function () {
        revealColor(colorList[value]);
    }, delay);
    delay += 1000;
});

function revealColor(color) {
    document.body.style.background = color;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>