admin管理员组

文章数量:1325767

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 plete.

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>

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 plete.

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>
Share Improve this question edited Dec 6, 2018 at 17:28 Shidersz 17.2k2 gold badges27 silver badges51 bronze badges asked Dec 3, 2018 at 21:15 Agnelio LhavanguaneAgnelio Lhavanguane 815 bronze badges 5
  • 4 Because that's what html() does. It replaces content – Taplar Commented Dec 3, 2018 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 – Shidersz Commented Dec 3, 2018 at 21:22
  • 2 Your wait function blocks the ui.. use window.setTimeout – Philipp Commented Dec 3, 2018 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 Commented Dec 3, 2018 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 Commented Dec 3, 2018 at 21:37
Add a ment  | 

2 Answers 2

Reset to default 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./ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>INITIAL TEXT...</p>
<br>
<button id="btnStop" type="button">Stop</button>

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();
};

本文标签: javascriptHow can I replace text dynamically time after timeStack Overflow