javascriptfor-loopinnertext

Change innertext of element dynamically inside for loop of a function


Issue : Upon entering a higher number like 10000, innertext of the new paragraph element is updated only after the for loop ends. Please help to make the innertext get updated for each number.

The increment function is called when an onchange event happens after sending a number as a input to the input element.

JAVASCRIPT :

function increment() {
    var count = document.getElementById('ac_count').value; //ac_count is the id of the input element
    var stat = document.createElement("p");
    stat.id = "current_status";
    stat.innerText = "";
    document.body.appendChild(stat);
    stat.style.display = "block";
    for (g = 1; g < count; g++) {
        stat.innerText = Number(g + 1) + " out of " + count + " records have been processed";
    }
}

Solution

  • The DOM doesn't redraw until the executing thread is free. You need to introduce async delays to your code to see a progressive update.

    function increment() {
      var count = document.getElementById('ac_count').value;
      var stat = document.createElement("p");
      stat.id = "current_status";
      document.body.appendChild(stat);
    
      var g = 1
      var itvl = setInterval(function() {
        update(g);
        g += Math.floor(Math.random() * 20) + 1
        if (g >= count) {
          clearInterval(itvl);
          update(count);
        }
      }, 10)
    
      function update(g) {
        stat.textContent = g + " out of " + count + " records have been processed";
      }
    }
    <input type=number value=10000 id=ac_count>
    <button onclick="increment()">CLICK ME</button>