How can I replace text dynamically time after time











up vote
6
down vote

favorite












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>









share|improve this question




















  • 4




    Because that's what html() does. It replaces content
    – Taplar
    Dec 3 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
    Dec 3 at 21:22






  • 2




    Your wait function blocks the ui.. use window.setTimeout
    – Philipp
    Dec 3 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 3 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 3 at 21:37















up vote
6
down vote

favorite












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>









share|improve this question




















  • 4




    Because that's what html() does. It replaces content
    – Taplar
    Dec 3 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
    Dec 3 at 21:22






  • 2




    Your wait function blocks the ui.. use window.setTimeout
    – Philipp
    Dec 3 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 3 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 3 at 21:37













up vote
6
down vote

favorite









up vote
6
down vote

favorite











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>









share|improve this question















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>






javascript jquery html






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 6 at 17:28









Shidersz

2,9981322




2,9981322










asked Dec 3 at 21:15









Agnelio Lhavanguane

313




313








  • 4




    Because that's what html() does. It replaces content
    – Taplar
    Dec 3 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
    Dec 3 at 21:22






  • 2




    Your wait function blocks the ui.. use window.setTimeout
    – Philipp
    Dec 3 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 3 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 3 at 21:37














  • 4




    Because that's what html() does. It replaces content
    – Taplar
    Dec 3 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
    Dec 3 at 21:22






  • 2




    Your wait function blocks the ui.. use window.setTimeout
    – Philipp
    Dec 3 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 3 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 3 at 21:37








4




4




Because that's what html() does. It replaces content
– Taplar
Dec 3 at 21:19




Because that's what html() does. It replaces content
– Taplar
Dec 3 at 21:19




3




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
Dec 3 at 21:22




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
Dec 3 at 21:22




2




2




Your wait function blocks the ui.. use window.setTimeout
– Philipp
Dec 3 at 21:22




Your wait function blocks the ui.. use window.setTimeout
– Philipp
Dec 3 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 3 at 21:23




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 3 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 3 at 21:37




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 3 at 21:37












2 Answers
2






active

oldest

votes

















up vote
7
down vote













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



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






$(document).ready(function()
{
// Define the time interval between executions (in milliseconds).
var _ivalTime = 3000;

var _strng = "Lorem ipsum dolor sit amet";
var _array = _strng.split(' ');
var _idx = 0;

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

// Check the restart (loop back) condition.

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

// Register listener on the click event of stop button.

$("#btnStop").click(function()
{
clearInterval(ival);
});
});

.as-console-wrapper {
max-height: 50% !important;
}

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>








share|improve this answer






























    up vote
    4
    down vote













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





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53601986%2fhow-can-i-replace-text-dynamically-time-after-time%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      7
      down vote













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



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






      $(document).ready(function()
      {
      // Define the time interval between executions (in milliseconds).
      var _ivalTime = 3000;

      var _strng = "Lorem ipsum dolor sit amet";
      var _array = _strng.split(' ');
      var _idx = 0;

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

      // Check the restart (loop back) condition.

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

      // Register listener on the click event of stop button.

      $("#btnStop").click(function()
      {
      clearInterval(ival);
      });
      });

      .as-console-wrapper {
      max-height: 50% !important;
      }

      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>








      share|improve this answer



























        up vote
        7
        down vote













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



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






        $(document).ready(function()
        {
        // Define the time interval between executions (in milliseconds).
        var _ivalTime = 3000;

        var _strng = "Lorem ipsum dolor sit amet";
        var _array = _strng.split(' ');
        var _idx = 0;

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

        // Check the restart (loop back) condition.

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

        // Register listener on the click event of stop button.

        $("#btnStop").click(function()
        {
        clearInterval(ival);
        });
        });

        .as-console-wrapper {
        max-height: 50% !important;
        }

        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>








        share|improve this answer

























          up vote
          7
          down vote










          up vote
          7
          down vote









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



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






          $(document).ready(function()
          {
          // Define the time interval between executions (in milliseconds).
          var _ivalTime = 3000;

          var _strng = "Lorem ipsum dolor sit amet";
          var _array = _strng.split(' ');
          var _idx = 0;

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

          // Check the restart (loop back) condition.

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

          // Register listener on the click event of stop button.

          $("#btnStop").click(function()
          {
          clearInterval(ival);
          });
          });

          .as-console-wrapper {
          max-height: 50% !important;
          }

          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>








          share|improve this answer














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



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






          $(document).ready(function()
          {
          // Define the time interval between executions (in milliseconds).
          var _ivalTime = 3000;

          var _strng = "Lorem ipsum dolor sit amet";
          var _array = _strng.split(' ');
          var _idx = 0;

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

          // Check the restart (loop back) condition.

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

          // Register listener on the click event of stop button.

          $("#btnStop").click(function()
          {
          clearInterval(ival);
          });
          });

          .as-console-wrapper {
          max-height: 50% !important;
          }

          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>








          $(document).ready(function()
          {
          // Define the time interval between executions (in milliseconds).
          var _ivalTime = 3000;

          var _strng = "Lorem ipsum dolor sit amet";
          var _array = _strng.split(' ');
          var _idx = 0;

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

          // Check the restart (loop back) condition.

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

          // Register listener on the click event of stop button.

          $("#btnStop").click(function()
          {
          clearInterval(ival);
          });
          });

          .as-console-wrapper {
          max-height: 50% !important;
          }

          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>





          $(document).ready(function()
          {
          // Define the time interval between executions (in milliseconds).
          var _ivalTime = 3000;

          var _strng = "Lorem ipsum dolor sit amet";
          var _array = _strng.split(' ');
          var _idx = 0;

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

          // Check the restart (loop back) condition.

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

          // Register listener on the click event of stop button.

          $("#btnStop").click(function()
          {
          clearInterval(ival);
          });
          });

          .as-console-wrapper {
          max-height: 50% !important;
          }

          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>






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 2 days ago

























          answered Dec 3 at 21:30









          Shidersz

          2,9981322




          2,9981322
























              up vote
              4
              down vote













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





              share|improve this answer

























                up vote
                4
                down vote













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





                share|improve this answer























                  up vote
                  4
                  down vote










                  up vote
                  4
                  down vote









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





                  share|improve this answer












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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 3 at 21:28









                  Philipp

                  13.2k22040




                  13.2k22040






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53601986%2fhow-can-i-replace-text-dynamically-time-after-time%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      數位音樂下載

                      格利澤436b

                      When can things happen in Etherscan, such as the picture below?