Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace text dynamically time after time

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>
like image 848
Agnelio Lhavanguane Avatar asked Dec 03 '18 21:12

Agnelio Lhavanguane


1 Answers

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>
like image 54
Shidersz Avatar answered Oct 07 '22 11:10

Shidersz