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









share|improve this question




















  • 4




    Because that's what html() does. It replaces content
    – Taplar
    6 hours ago






  • 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
    – D. Smania
    6 hours ago






  • 2




    Your wait function blocks the ui.. use window.setTimeout
    – Philipp
    6 hours ago










  • 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
    6 hours ago










  • 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
    5 hours ago















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









share|improve this question




















  • 4




    Because that's what html() does. It replaces content
    – Taplar
    6 hours ago






  • 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
    – D. Smania
    6 hours ago






  • 2




    Your wait function blocks the ui.. use window.setTimeout
    – Philipp
    6 hours ago










  • 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
    6 hours ago










  • 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
    5 hours ago













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









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






javascript jquery html






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 5 hours ago









D. Smania

2,7901321




2,7901321










asked 6 hours ago









Agnelio Lhavanguane

312




312








  • 4




    Because that's what html() does. It replaces content
    – Taplar
    6 hours ago






  • 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
    – D. Smania
    6 hours ago






  • 2




    Your wait function blocks the ui.. use window.setTimeout
    – Philipp
    6 hours ago










  • 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
    6 hours ago










  • 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
    5 hours ago














  • 4




    Because that's what html() does. It replaces content
    – Taplar
    6 hours ago






  • 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
    – D. Smania
    6 hours ago






  • 2




    Your wait function blocks the ui.. use window.setTimeout
    – Philipp
    6 hours ago










  • 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
    6 hours ago










  • 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
    5 hours ago








4




4




Because that's what html() does. It replaces content
– Taplar
6 hours ago




Because that's what html() does. It replaces content
– Taplar
6 hours ago




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
– D. Smania
6 hours ago




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
– D. Smania
6 hours ago




2




2




Your wait function blocks the ui.. use window.setTimeout
– Philipp
6 hours ago




Your wait function blocks the ui.. use window.setTimeout
– Philipp
6 hours ago












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
6 hours ago




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
6 hours ago












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
5 hours ago




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
5 hours ago












2 Answers
2






active

oldest

votes

















up vote
5
down vote













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 = _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.

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 TEXT...</p>








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
      5
      down vote













      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 = _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.

      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 TEXT...</p>








      share|improve this answer



























        up vote
        5
        down vote













        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 = _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.

        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 TEXT...</p>








        share|improve this answer

























          up vote
          5
          down vote










          up vote
          5
          down vote









          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 = _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.

          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 TEXT...</p>








          share|improve this answer














          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 = _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.

          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 TEXT...</p>








           $(document).ready(function()
          {
          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.

          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 TEXT...</p>





           $(document).ready(function()
          {
          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.

          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 TEXT...</p>






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 2 mins ago

























          answered 6 hours ago









          D. Smania

          2,7901321




          2,7901321
























              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 6 hours ago









                  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

                      Accessing regular linux commands in Huawei's Dopra Linux

                      Can't connect RFCOMM socket: Host is down

                      Kernel panic - not syncing: Fatal Exception in Interrupt