Search code examples
javascriptbrowserrendersingle-threaded

Can I force the browser to render DOM changes during javascript execution


Is there a way to force the browser to render DOM changes during the execution of JavaScript? In the following example, only the '1000' will be displayed and I do understand that this is caused by having only a single thread processing the JavaScript executing but I was wondering if there is a way to force the browser to render each DOM change?

Example:

var el = document.getElementById("#fixup"),
   i;

for (i = 1; i <= 1000; i++) {
   // can i force this DOM update to the rendered?
   el.innerHTML = i.toString());
}

Solution

  • You can do it with timers. Here's an example:

    var el = document.getElementById("fixup");
    var speed = 10;
    for (var i = 1; i <= 1000; i++) {
      setTimeout(function(i) {
          el.innerHTML = i;
      }, speed * i, i);
    }
    <div id="fixup"></div>

    Probably not the best way though, having 1000 timers from the get go is kind of fishy.

    An alternative:

    var el = document.getElementById("fixup");
    var speed = 10, i = 0, limit = 1000;
      setTimeout(function loop() {
          el.innerHTML = i++;
          if(i <= limit){
            setTimeout(loop, speed);
            }
      }, speed);
    <div id="fixup"></div>

    Ultimately this would be the best if you don't care for the speed at which elements are rendered:

    var el = document.getElementById("fixup");
    var speed = 10, i = 0, limit = 1000;
      window.requestAnimationFrame(function loop() {
          el.innerHTML = i++;
          if(i <= limit){
            window.requestAnimationFrame(loop);
            }
      });
    <div id="fixup"></div>