Try to randomize the words in a table and stop the loop after 5

advertisements

I'm trying to write a script that will pick a random word from an array called words, and stop the loop after 5 times and replace the html with Amazing. so it always ends on amazing. Can't figure out best practice for something like this. My thinking is there just don't know where to put the script ender or how to properly implement this.

I feel like I need to implement something like this into my script, but can't figure out where. Please help.

if(myLoop > 15) {
    console.log(myLoop);
    $("h1").html('AMAZING.');
}
else {
}

Here is the Javascript that I'm using to loop and create bring new words in.

$(document).ready(function(){

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

    var timer     = 2000,
        fadeSpeed =  500;

    var count = words.length;
    var position, x, myLoop;

    $("h1").html(words[rand(count)]);

    function rand(count) {
        x = position;
        position = Math.floor(Math.random() * count);
        if (position != x) {
            return position;
        } else {
            rand(count);
        }
    }

    function newWord() {
        //clearTimeout(myLoop); //clear timer

        // get new random number
        position = rand(count);

        // change tagline
        $("h1").fadeOut(fadeSpeed, function() {
            $("h1").slideDown('slow'); $(this).html(words[position]).fadeIn(fadeSpeed);
        });

        myLoop = setTimeout(function() {newWord()}, timer);
    }

    myLoop = setTimeout(function() {newWord()}, timer);
});

Here's my codepen

http://codepen.io/alcoven/pen/bNwewb


Here's a solution, which uses a for loop and a closure.

Words are removed from the array using splice. This prevents repeats.

I'm using jQuery delay in place of setTimeout:

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

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

fadeSpeed =  500;
timer = 2000;

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

  (function(word) {
    $('h1').fadeOut(fadeSpeed, function() {
             $(this).html(word);
           })
           .slideDown('slow')
           .delay(timer)
           .fadeIn(fadeSpeed);
   }
  )(word);
}
h1 {
  text-transform: uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>