Frankenmint Frankenmint - 6 months ago 31
HTML Question

how do I update innerHTML in a for loop using a while loop?

Thought I had this in the bag...guess I was wrong:

Expected behavior - page loads, then for each element in the array it updates my innerHTML value using setTimeout

Observed behavior - On my hosting it seems to update the value just one time, then it breaks my css before becoming unresponsive. I threw in an alert to see if it's ever running on jsFiddle and it appears to not be running so there's also that

Answer

There's absolutely no need to set synchronous multiple timeouts inside a loop.
Use only a single setInterval or recall a function than has a single setTimeout

You could easily do this using setInterval()

jQuery(function($){

  var $btn = $("#ctaButton"),
      ctaList = ['Get Started Today', 'Complementary Quotes', 'Book Your Consultation'],
      tot = ctaList.length,
      c = 0; // iterations counter
  
  function changeCTAtext(){
    $btn.html( ctaList[++c%tot] );
  };

  setInterval(changeCTAtext, 1000); // Start

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button  id="ctaButton">Get Started Today</button>

Using setTimeout() it's like this:

jQuery(function($){

  var $btn = $("#ctaButton"),
      ctaList = ['Get Started Today', 'Complementary Quotes', 'Book Your Consultation'],
      tot = ctaList.length,
      c = 0; // iterations counter
  
  function changeCTAtext(){
    $btn.html( ctaList[c++%tot] );
    setTimeout(changeCTAtext, 1000); // ...and repeat every NNNms
  };

  changeCTAtext(); // Start

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button  id="ctaButton">Get Started Today</button>

Comments