Manually write a progress bar

Manually implement a progress bar, the length of each movement of the progress bar random, random movement time, slowly to 40% over time, to about 80% will stop, waiting for the completion of loading the real

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div style="border: 1px solid red;width: 600px;height: 20px;line-height: 20px;">
    <div id="myDiv2" style="background-color: lightblue;width: 0;height: 20px;line-height: 20px;">0%</div>
  </div>
  
<button id="btn">run</button>
<button id="btn2">run2</button>
</body>
</html>
<script>
  var timer;
  btn.onclick = function(){
    cancelAnimationFrame(timer)
    clearTimeout(set)
    requestAnimationFrame(()=>{yy(true)})
  }
  var timer //requestAnimationFrame
  var set //settimeout的索引
  var yan = 0 //记录状态用于40%左右的卡顿
  btn2.onclick = function(){
    timer = requestAnimationFrame(()=>{yy()})
  }
  function ran(m,n){
    return Math.floor(Math.random()*(n-m)+m)
  }
  function yy(im){ 
      if(parseInt(myDiv2.style.width)<600){
        //生成随机增量
    var nu = ran(0,100)
    var jia = 600*(nu/1000)
    var tt = ran(0,300)
    if (parseInt(myDiv2.style.width)<600*0.8 || im) {
      let width = parseInt(myDiv2.style.width)+jia  
      if (width>240 && yan==0 ) {
        yan=1
      }else if(width>240 && yan==1 ){
        yan=2
      }
      console.log(yan)
      set = setTimeout(() => {
        myDiv2.style.width = (width >600)?600 + 'px': width+'px'
          myDiv2.innerHTML = parseInt(myDiv2.style.width)/6>100?100+ '%': (parseInt(myDiv2.style.width)/6).toFixed(2)+ '%'
          timer = requestAnimationFrame(()=>{yy(im)})
      },im?10:( yan===1?ran(800,1000):tt));
    } else  {
      cancelAnimationFrame(timer)
    }
      }else{
        cancelAnimationFrame(timer)
      }
    }
  </script>

Guess you like

Origin www.cnblogs.com/wzcsqaws/p/11109643.html