简体   繁体   中英

How to make pause between each for loop iteration in JavaScript

I'm sorry if there has already been such question, I haven't found.

I wanna make a progress (loading) animation with JS:

   <div class = "load">

     <div id = "load_fill"></div>

     <p id = "percent">0%</p>

   </div>
        
   
   
   <script>
     
     let percent = document.getElementById("percent");
     let load_fill = document.getElementById("load_fill")
     
     
     
     let j = 0;
     
     let fill = ()  => {
       
       j++;

       percent.textContent = `${j}%`;

       load_fill.style.width = `${j}%`
       
     }

     
     for (let i = 0; i < 100; i++){
       
       setTimeout(fill, 200);
       
     }
     
     
   </script>

The problem is that the first iteration works with delay but others no;

Is there any way to make delay between each iteration?

Will be thankful for any answer.

new Array(100).map((el, ind) => ind).forEach((cur) => setTimeout(fill, (cur + 1) * 200))

Here, we space out each setTimeout by first creating a range array (the first part) before setting a time out 200 ms between each one.

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