Is There A Way To Update Dom Element From Within A For Loop?
Solution 1:
The "problem" which arises here, is that ECMAscript is a single-threaded process. In most cases, ECMAscript code runs within the such called "UI Thread". As you already might have guessed by the name, other processes, like updating and visualising DOM components (including CSS changes), are also running in this very process. Now, without going into greater detail, what happens here basically looks like:
[ HTML:DOM Rendered - UI UPDATE- JS:LOOP(100000) - UI UPDATE ]
Since your entire loop runs synchronously, there is no chance for the UI Thread to show any rendered updates. Your only chance to achieve that is to manually interrupt your loop from time to time.
There are several ways to do this, the most simple one is probably the use of setTimeout()
.
You could re-write your code into:
let i = 0;
(functionloop() {
const li = document.createElement('li');
li.innerHTML = i++;
parentUL.appendChild(li);
if( i < 100000 ) {
setTimeout(loop, 20);
}
}());
What happens now, is that the execution of your JS code gets interrupted every 20 milliseconds and the UI Thread can update whatever visual changes are necessary.
[ HTML:DOM Rendered - UI UPDATE- loop() - UI UPDATE- loop() - UI UPDATE- ... ]
Solution 2:
although 100000 is a high number such for/loop doesn't take longer den some milliseconds. And due to better performance and user experience, browsers optimize refresh rate for such changes. If you want to have a visible time difference between each append, you may add timeout like this:
const parentUL = document.querySelector('#unordered-list');
for (let i = 0; i < 100000; i++) {
const li = document.createElement('li');
li.innerHTML = i;
setTimeout(()=>{
parentUL.appendChild(li);},i * 250);
})
}
Post a Comment for "Is There A Way To Update Dom Element From Within A For Loop?"