2
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!

1 Answer 1

4

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>

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

1 Comment

This is perfect! Increasing the delay in every pass of the loop allows it to have the desired behavior. Thanks!

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.