Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
}
like image 332
doberkofler Avatar asked Sep 26 '22 05:09

doberkofler


1 Answers

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>
like image 138
MinusFour Avatar answered Oct 30 '22 01:10

MinusFour