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

后端 未结 3 1183
一生所求
一生所求 2021-01-24 08:48

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 chang         


        
3条回答
  •  悲哀的现实
    2021-01-24 09:08

    var whatAmI = ["Webdesigner", "Drummer", "Techie", "Linguistics student", "Photographer", "Geek", "Coder", "Belgian", "Batman", "Musician", "StackExchanger", "AI student"];
    
    var prev = 1; //1 because "drummer" is the first array element displayed in the HTML
    
    function getIndex(){
        var next = Math.floor(Math.random() * whatAmI.length);
        if(next==prev)
            return getIndex();
        else {
            prev = next;
            return next;
        }       
    }
    
    function changeSubTitle() {
        setTimeout(function () {
            $(".page-header > h2").animate({
                "opacity": 0
            }, 700, function () {
                $(this).text(whatAmI[getIndex()]);
                $(this).animate({
                    "opacity": 1
                }, 700, changeSubTitle);
            });
        }, 1000);
    }
    changeSubTitle();
    

    Try this method.

提交回复
热议问题