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


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) {
else {

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


    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;


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

    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

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() {
h1 {
  text-transform: uppercase;
<script src=""></script>