Looking for help with a script that randomly selects words from an array and stops after 5 iterations, always ending on the word "Amazing." Struggling to figure out the best approach - any advice on how to properly implement this would be appreciated.
I believe I need to incorporate something like this into my script but unsure where. Assistance is needed.
if(myLoop > 15) {
console.log(myLoop);
$("h1").html('AMAZING.');
}
else {
}
Sharing the JavaScript code used to loop through and display new words:
$(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);
});
For reference, here's my Codepen link: