How can I replace text dynamically time after time

  • A+
Category:Languages

I want to replace the content of a paragraph using items from an array dynamically time after time. The output is fine when I use console.log() to check the results. But it is not replacing the content on the paragraph as expected, just shows the last word when the iteration is complete.

Here is my code to create and iterate an array:

$(document).ready(function() {     var _strng = "Lorem ipsum dolor sit amet";     var _array = new Array();     _array = _strng.split(' ');      jQuery.each(_array, function(index,item)     {         console.log(item); //works fine         $('p').html(item); //only shows the last word when the iteration is over         wait(1000); //custom function         console.clear();     }); }); 

The wait() function:

function wait(_timeframe) {     var final = 0;     var timeframe = new Date(_timeframe);         var initial = Date.now();     final = initial + _timeframe;      while (Date.now() < final) { }; } 

HTML code:

<p>Text to be replaced here</p> 

 


Check the next example, using the setInterval() method, it will replace the text of the <p> element every 3 seconds, looping back to the start of the array when it reach the end.

 $(document).ready(function()  {     var _strng = "Lorem ipsum dolor sit amet";     var _array = new Array();     _array = _strng.split(' ');     var _idx = 0;          var timer = setInterval(function()     {         var item = _array[_idx++];         console.log(item);         $('p').html(item);          // Check the restart condition.                  if (_idx >= _array.length)             _idx = 0;     },     3000); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <p>INITIAL STATE</p>

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: