vendredi 4 septembre 2015

Get random element from array, display it, and loop - but never followed by the same element

I wrote a simple enough randomize function that loops through the elements in an array and displays them one after the other.

See it here.

function changeSubTitle() {
    var whatAmI = ["Webdesigner", "Drummer", "Techie", "Linguistics student", "Photographer", "Geek", "Coder", "Belgian", "Batman", "Musician", "StackExchanger", "AI student"];
    setTimeout(function () {
        $(".page-header > h2").animate({
            "opacity": 0
        }, 700, function () {
            $(this).text(whatAmI[Math.floor(Math.random() * whatAmI.length)]);
            $(this).animate({
                "opacity": 1
            }, 700, changeSubTitle);
        });
    }, 1000);
}

However, obviously it is very well possible that the same element is displayed twice, one immediately after the other. This happens because I randomize the array each time I call the function. How would I prevent an element to be displayed two times right after each other?

I suppose the most straightforward way to do this is to get the randomize function out the loop, run the loop and each time an element is called, remove the index from the array and refill the array when it's empty. A lot of questions on SO consider this problem, but not as specific as mine: I'm not sure how to do this in the loop to display each element.




Aucun commentaire:

Enregistrer un commentaire