Attempting to shuffle words in an array and halt the iteration after reaching 5

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:

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

Answer №1

Check out this innovative solution that utilizes a for loop along with a closure.

In order to prevent repeats, words are deleted from the array using the splice method.

The code snippet below leverages jQuery's delay instead of using 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>

Answer №2

To keep track of the number of iterations, I implemented a counter in my code.

I introduced the iteration counter as one of the additional variables:

var iter = 1;

The following snippet displays how I incorporated the counter within the newWord function:

iter = iter + 1;
if (iter > 5) {
  return;
}

var word;
if (iter == 5) {
  word = 'awesome';
}
else {
...

If you would like to view my revised solution, please click on the link below:

http://codepen.io/anon/pen/YPGWYd

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript to skip duplicate rows in an HTML table based on group

My current task involves fetching multiple data from a database using AJAX and PHP. Once I retrieve the data successfully, I need to group the results in a specific format like the images shown below, including having a textarea field for each group. Here ...

What is the best method for retrieving the character's ID from within an object?

Exploring my collection of movies, I discovered that each movie contains an array of characters. My goal is to display specific information about each character (such as their name and age) when clicked on, requiring me to obtain the id of each character. ...

How can I determine if a specific button has been clicked in a child window from a different domain?

Is there a method to detect when a specific button is clicked in a cross-domain child window that cannot be modified? Or determine if a POST request is sent to a particular URL from the child window? Below is an example of the HTML code for the button tha ...

Using Three.js to shift an object toward a specific point on a line and adjust its orientation with lookAt

I am working with a cuboid (such as THREE.CubeGeometry 1x1x10) and I have a specific goal in mind: My objective is to position the cuboid at a certain distance from the origin, along the line connecting the origin and a given point I also want to rot ...

Bootstrap is not being rendered by Express

As I venture into learning Express, I've come across an issue regarding the rendering of Bootstrap fonts in my application. Despite setting up the correct paths, the font appears as simple Times New Roman instead of the desired Bootstrap font when run ...

Unable to shake off a sudden burst of information following the ajax page load

I am facing an issue with my page that involves making different ajax calls based on user clicks. There are four IDs, and only one should be visible at a time. However, when new ajax content is loaded into a div, I experience a brief flash of the previou ...

Is it possible to integrate the screenfull JavaScript library into the Next.js framework?

Attempting to utilize Dynamic Importing in Nextjs for incorporating the screenfull library has proven unsuccessful. import dynamic from "next/dynamic" import screenfull from 'screenfull'; const Screenfull = dynamic(()=>{return import ...

Adjust the placement of an HTML component using Angular 2

My angular component template includes: <my-app> <nav id="nav-bar"> <ul> <li id="item-1"></li> <li> <div id="item-2"></div> </li> <li id="item-3"></li> ...

Exploring a JSON API structure with the help of jQuery

I am currently exploring the world of JSON API and attempting to extract some data. As a beginner, I find myself struggling to identify the exact value to use. Here is an example of the JSON API I am dealing with: [ {"lang":"english","visual":"<span ...

React Router leading to incorrect destination

Currently, I am working on developing a single page application using React and React Router. One issue I have encountered is when navigating to different pages, such as "/banners" and then going to "/banners/edit/1234", everything functions correctly. Ho ...

Tips for retrieving the key of a Firebase Object

I'm looking for a way to retrieve the key of a Firebase object without relying on snapshot data. After some investigation, I used the following code: var ref = new Firebase('https://johnsoncompany.firebaseio.com/people') var firstPerson = ...

Error: missing semicolon prior to the statement

I am looking to create a Java web application that includes a JSP page. However, when I load the page, I encounter the following error: SyntaxError: missing ; before statement The code for my JSP page is as follows: <%@ page language="java" contentTy ...

Increase the time of a Date by 10 seconds

Is there a way to increase the time of a JavaScript date object by 10 seconds? For example: var currentTime = new Date(); var currentSeconds = currentTime.getSeconds() + 10; currentTime.setSeconds(currentTime.getSeconds() + currentSeconds); ...

What is the method by which jQuery achieves synchronous behavior in its $.ajax function?

I previously asked a similar question on Stack Overflow, but I wanted to approach it from a different angle to get more feedback. So far, I haven't found a solution that works for me. I am trying to make XCode execute a JavaScript command and receive ...

The Stepper StepIconComponent prop in MUI is experiencing issues when trying to render styles from the styles object, leading to crashes in the app

Struggling to find a way to apply the styles for the stepper component without using inline styles. I attempted to replicate Material UI's demo, but encountered an error. The code from Material UI's demo that I want to mimic is shown below: http ...

Challenges with using async await alongside synchronous functions

I'm currently navigating through a library that utilizes async functions and feeling a bit overwhelmed. I'm attempting to call a function that should return a string, but I'm hitting some roadblocks. As I understand it, the ZeroEx library fu ...

"Oops, we hit a snag" notification appears when attempting to share on Facebook using the share dialog

I am currently integrating Django with Facebook for page sharing. Below is the code snippet I am using to form the URL: var link = 'https://www.facebook.com/dialog/feed?app_id=1234567890&display=popup&name=' + name + '&descripti ...

Learn the best method for transferring product images and audio files between pages without the need for hardcoding

With the assistance of individuals from Stack Overflow, I managed to create a function that displays products added to the cart. Now, I am looking to enhance it so that it can also show product images and audio files without any hardcoding! On my product ...

The utilization of the Angular date pipe significantly impacts the way dates are

When I use the pipe date:'MM/dd/YYYY' to display the date 2022-01-01T00:00:00, it shows as 1/01/2021 instead of 1/01/2022. This issue only occurs with this specific date. Why does this happen? The value of pharmacyRestrictionDate is 2022-01-01T0 ...

HtmlUnitDriver fails to execute javascript while loading a page from a URL

My issue revolves around testing my website page, where elements displayed with javascript are missing when viewed through the HtmlUnitDriver. I am currently using selenium-java version 3.141.59 and htmlunit-driver version 2.33.3. Below is a snippet of my ...