0

I want to cycle through an array and display each element individually, and then remove it. Sort of like this fiddle, but I don't want it to go forever.

I tried using jQuery because I thought it would be easier, but I am clearly missing something. Can anyone help?

Here is my attempt, but it just goes straight to the last element in the array.

var list = [1,2,3,4,5,6];
var length = list.length;

for(i = 0; i < length; i++) {
    $('#nums').html(list[i]).delay(750);
}

Oh, and I don't care if it's jQuery or vanilla JavaScript. Either is fine by me.

1

3 Answers 3

1
$(document).ready(function(){
    var list = [1,2,3,4,5,6];
    var length = list.length;

    var i = 0;

    var ivl = setInterval( function () {
        if (i < length) {
            $('#nums').html(list[i]).delay(750);
            i++;
        }
        else {
            clearInterval(ivl);
        }            
    }, 750);
});
Sign up to request clarification or add additional context in comments.

2 Comments

All I did was to use setInterval, some loop control, then clearInterval when done.
I really like this answer. Thank you. I love how many options programming provides to find solutions to the same problem.
1

The (pretty clever) example uses the fact that the modulus operator (%) gives you remainder, which is periodic, so you can use it to cycle through your array by taking the remainder of an infinitely increasing number divided by the length of your list.

If you want it to stop, however, you can just do a check to see if you've finished cycling through the list:

var list = [1, 2, 3, 4, 5, 6];
var length = list.length;
var i = 0;
var finished = false;

function repeat() {
  if (!finished) {
    document.getElementById('nums').innerHTML = list[i % length];
    i++;
    if (i === length) {
      finished = true;
    }
  } else {
    clearInterval(interval);
  }
}

var interval = setInterval(repeat, 750);
<div id="nums"></div>

Comments

1

Late to the party but wouldn't it be better to use setTimeout rather than setInterval just in case the code executed on each iteration takes longer than the interval duration? I mean, I know it's not an issue in this instance but it's just a better/safer way to do this sort of thing.

$(document).ready(function(){
    var list = [1,2,3,4,5,6];
    var length = list.length;
    var i = 0;
    (function next(){
        if (i < length){
            $('#nums').html(list[i++]);
            setTimeout(next,750);
        }
    })();
});

http://jsfiddle.net/zLexhdfp/3/

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.