简体   繁体   中英

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

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> 

看看这里for性能测试,你会发现for循环非常快,它可以在~0.135秒内循环1000,所以如果要显示所有迭代,你必须使用setTimedout()来减慢操作。

If you are only supporting chrome if you call

alert("check the box to prevent these")

and it will update the DOM every time it is called but if other browsers come on it could be very annoying

If you are trying to have DOM show 1-1000, then create a div object every loop and appendChild() to your el. Then instead of showing 1000, you can see 1- 1000.

inside of the forloop,

var newDiv = document.createElement("div");
newDiv.innerHTML = i;
el.appendChild(newDiv);

and out of the loop. Basically, every time it loops, you are creating a new div, assigning the value to (this) newDiv, and appending it the parent node. I hope this helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM