Quickly solve the problem of timely rendering of pages after js dynamically changes the attributes of dom elements

  • 2021-07-01 06:38:06
  • OfStack

Today, to implement a progress bar loading process, the dom structure is actually two div


<div class="pbar">
 <div class="ui-widget-header" id="percent_bar" style="width: 23%;"></div>
 </div>

By controlling the wide width attribute of the inner div, the progress bar can move forward.

My progress bar is to show the progress of downloading files. If you simply realize 1 total of 100 files, you will download 1%, and you will go to 20% after downloading 20. So the code is implemented as follows:


var fileCount=fileList.length();
 fileList.foreach(function(i,obj){
   ........// Download a file 
  document.getElementById("percent_bar").style.width=i/fileCount*100 + "%";// Change the inner layer div Width of 
 })

However, you will see that the files are downloaded one by one, but the progress has never moved one. This is because js logic takes precedence, and page rendering takes place after js execution, so you can't see a normal progress bar.

How can js logic perform such a first-class page rendering?


var i=0;
var fileCount=fileList.length();
var loop = function () {
 if(i>fileCount)// Exit loop 
    return;
  .....// Download a file 
  i++;
  document.getElementById("percent_bar").style.width=i/fileCount*100+"%";
       // Under 1 Step cycle   that.loopId = window.setTimeout(loop, 0);7 }
that.loopId = window.setTimeout(loop, 0);

The dynamic effect of progress bar can be realized through settimeout function.


Related articles: