Home > front end >  Looping through an array using if then statements using JavaScript
Looping through an array using if then statements using JavaScript

Time:04-13

I am very new here and new to code. I not know anyone who can help me with this and have watched allot of youtube videos on how to try and solve my problem. I am trying to loop through the array below using if then and else statements and the function cardCounter. I want the the items in the array to individually appear on the screen and then disappear one after the other. Right now my array just looks like lines of text on a screen when opened in my browser.

This is my code:

 <script>
     const calm1 = [];
         calm1[0]= "Silence is the element in which great things fashion themselves 
          together. —Thomas Carlyle";
         calm1[1]= "Take a deep breathe in and count to 7 seconds ";
         calm1[2]= "Take a slow exhale out";
         calm1[3]= "Self-care is not selfish. You cannot serve from an empty vessel.– Eleanor Brown";
         calm1[4]= "Loneliness is a sign you are in desperate need of yourself.― Rupi Kaur,";
         calm1[5]= "do not look for healingat the feet of thosewho broke you― Rupi Kaur,";
         calm1[6]= "if you were born with the weakness to fall you were born with the strength to rise― Rupi Kaur";
         calm1[7]= "you kill your future by mourning the past― R.H. Sin";
         calm1[8]= "Our backs tell stories no books have the spine to carry― Rupi Kaur";
         calm1[9]= "what is stronger than the human heart which shatters over and over and still lives― Rupi Kaur";
         calm1[10]= "the world gives you so much pain and here you are making gold out of it- there is nothing purer than that― Rupi Kaur";
         calm1[11]= "fall in love with your solitude― Rupi Kaur";
         calm1[12]= "You do not just wake up and become the butterfly -Growth is a process.― Rupi Kaur";
         document.getElementById("calm").innerHTML = calm1;

     var words = document.getElementById('calm');
     var text = -1;
     function cardCounter () {
        text  ;
        if (text<calm1.length) {
            words = calm1[text];
        }
        else {
            words = -1;
            clearInterval(intervalTimer);
        }

     ;}  
     var intervalTimer = setInterval(function(){cardCounter()},5000);

 </script>
 
 

CodePudding user response:

Welcome to StackOverflow and the wonderful world of JavaScript programming!

The If/Then/Else construct does not allow for iteration over a collection of objects, instead it only handles decision making. (IF some condition is met THEN do some action ELSE do something else)

What you are looking for is a loop of some kind, usually for this case you would use a FOR loop.

Your function would look something like this. I have changed some of the variable names to generalise them for others.

// Populate the statements as before
const statements = [];
// Get a reference to the HTML element you want to change
const calmElement = document.getElementById('calm');
// Create a timer function that will resolve after a specified number of milliseconds
const timer = ms => new Promise(res => setTimeout(res, ms))

// Define the function as asynchronous, meaning it will contain an awaited function call
async function cardCounter(delay) {
  // Iterate over every statement in our list and do something with each one.
  for(const statement of statements) {
    // Now we have access to a statement, we can set the HTML element text property to be our next statement
    calmElement.innerText = statement;
    // Call the timer method we created above, this will halt execution for X milliseconds
    await timer(delay);
  } 
}

Now you can call your function whenever you want to start the quotes running through

cardCounter(5000);

Credit to this stackoverflow post for setting up the timer.

CodePudding user response:

It looks like you're trying to update some text in a div on a timer. While there are a number of ways to do this, here's one example.

const calm = [
  "Silence is the element in which great things fashion themselves together. —Thomas Carlyle",
  "Take a deep breathe in and count to 7 seconds ",
  "Take a slow exhale out",
  "Self-care is not selfish. You cannot serve from an empty vessel.– Eleanor Brown",
  "Loneliness is a sign you are in desperate need of yourself.― Rupi Kaur,",
  "do not look for healingat the feet of thosewho broke you― Rupi Kaur,",
  "if you were born with the weakness to fall you were born with the strength to rise― Rupi Kaur",
  "you kill your future by mourning the past― R.H. Sin",
  "Our backs tell stories no books have the spine to carry― Rupi Kaur",
  "what is stronger than the human heart which shatters over and over and still lives― Rupi Kaur",
  "the world gives you so much pain and here you are making gold out of it- there is nothing purer than that― Rupi Kaur",
  "fall in love with your solitude― Rupi Kaur",
  "You do not just wake up and become the butterfly -Growth is a process.― Rupi Kaur"
];

// set the index to the first element
let index = 0;

// set the text in the calm div with the text at the index
function setText(index) {
  document.getElementById("calm").innerText = calm[index];
}

// set initial text
setText(index);

// setup a timer to rotate text every 5 seconds
setInterval(() => {
  // advance index, if index would roll off end of array, start over
  if (index   1 == calm.length) index = 0;
  else   index;
  
  // set the text
  setText(index);
}, 5000);
<html>

<body>

  <div id="calm">

  </div>
</body>

</html>

  • Related