8

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 the code I made to create and iterate over the 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>
Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • 4
    Because that's what `html()` does. It replaces content – Taplar Dec 03 '18 at 21:19
  • 3
    There exists `setInterval()` and `setTimeout()` functions on Javascript for your purposes, avoid using a custom wait. Here is a good tutorial for you: [Timing On JS](https://www.w3schools.com/js/js_timing.asp) – Shidersz Dec 03 '18 at 21:22
  • 2
    Your `wait` function blocks the ui.. use `window.setTimeout` – Philipp Dec 03 '18 at 21:22
  • i think you are trying to append, not replace all the p tags with all elements (the last will be final as there are no more itterations – DarkMukke Dec 03 '18 at 21:23
  • Show us the `wait()` function, please. I suspect it makes use of `setTimeout()` which is delayed execution, so really everything would just happen at once in the future. – Mark Carpenter Jr Dec 03 '18 at 21:37

2 Answers2

9

You can use setInterval() method for this approach. On the next example, we use it to replace the text of the <p> element every N seconds, looping back to the start of the array when it reach the end.

Also, there is a button to show how to stop the execution of this procedure using the clearInterval() method (just in case you need to learn about it).

$(document).ready(function()
{
    var _str = "Lorem ipsum dolor sit amet";
    var _array = _str.split(' ');
    var _idx = 0;

    // Define the time interval between executions (in milliseconds).

    var _ivalTime = 3000;

    // Define the method that will change the text.

    var changeText = function()
    {
        var item = _array[_idx++];
        console.log(item);
        $('p').html(item);

        // Check the restart (loop back) condition.

        _idx = (_idx >= _array.length) ? 0 : _idx;
    };

    // Start the procedure to change text.

    var ival = setInterval(changeText, _ivalTime);

    // Register listener on the click event of stop button.
    
    $("#btnStop").click(function()
    {
        clearInterval(ival);
    });
});
.as-console-wrapper {max-height:50% !important;}
.as-console {background-color:black !important;color:lime;}

p {
  background: skyblue;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>INITIAL TEXT...</p>
<br>
<button id="btnStop" type="button">Stop</button>
Shidersz
  • 16,846
  • 2
  • 23
  • 48
4

The problem is, that you wait functions blocks the ui. Instead, you should use window.setTimeout, which calls a callback after a specific time.

You could try something like this for your problem

$(function() {
    var words = ["Lorem", "ipsum", "dolor"];
    var $element = $("p");

    // callback function
    var f = function() {
        $element.html(words.shift());
        if (words.length > 0) {
            window.setTimeout(f, 1000);
        }
    }

    // initial call
    f();
};
Philipp
  • 15,377
  • 4
  • 35
  • 52