Search code examples
javascriptrandomwords

Can't get my word randomizer script to loop properly


I'm trying to get this script to run, than end on the word Awesome. and then loop again/repeat.

Here's the JS

var i, word, rnd, words, fadeSpeed, timer;

words = ['respected​.', 'essential.', 'tactical.', 'effortless.', 'credible.', 'smart.', 'engaging.', 'focused.', 'effective.', 'clear.', 'relevant.', 'strategic.', 'trusted.', 'compelling.', 'admired.', 'inspiring.', 'cogent.', 'impactful.', 'valued.'];

fadeSpeed = 500;
timer = 2000;

for (i = 0; i < 20; i++) {
    if (i === 19) {
        word = 'awesome.';
        rnd = Math.floor(Math.random() * words.length);
        word = words[rnd];
        words.splice(rnd, 1);
    } else {
        rnd = Math.floor(Math.random() * words.length);
        word = words[rnd];
        words.splice(rnd, 1);
    }

    (function(word) {
        $('h1.random em').fadeOut(fadeSpeed, function() {
                $(this).html(word);
            })
            .slideDown('slow')
            .delay(timer)
            .fadeIn(fadeSpeed);
    })(word);
}

Here's a link to the dev site.

http://dev-pivot-website.pantheon.io/#


Solution

  • Splice will remove word from your array .

    words.splice(rnd, 1);  
    

    After the 20th element there is nothing left to iterate.

    As @Jamiec said you will need a continuous loop. You can also use setTimeout(); to loop continuously (should be less CPU heavy than while(true) )

    Try something like this (slightly modified version of @jamiec's answer)

       var i, word, rnd, words, fadeSpeed, timer;
    
    function getWords(){
    var words = ['respected​.', 'essential.', 'tactical.', 'effortless.', 'credible.', 'smart.', 'engaging.', 'focused.', 'effective.', 'clear.', 'relevant.', 'strategic.', 'trusted.', 'compelling.', 'admired.', 'inspiring.', 'cogent.', 'impactful.', 'valued.'];
        return words;
    }
    
    words = getWords();
    fadeSpeed = 500;
    timer = 2000;
    
    displayWords();
    
    
    
    function displayWords(){
      var word;
      if(words.length == 0){
          word = "awesome.";  
          words = getWords();      
      }
      else{
        rnd = Math.floor(Math.random() * words.length);
        word = words[rnd];
        words.splice(rnd, 1);
      }
    
      (function(word) {
            $('h1.random em').fadeOut(fadeSpeed, function() {
                    $(this).html(word);
                })
                .slideDown('slow')
                .delay(timer)
                .fadeIn(fadeSpeed);
        })(word);
    
        setTimeout(displayWords,1000);
    }
    

    Fiddle : http://jsfiddle.net/198ke25u/3/