es6高阶函数使用-数值动画函数

0 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <div id="content">
        
    </div>
    
</body>
  <script>

         let content=document.getElementById("content").innerHTML="Hello World"
         const animates=(duration,from,to,callback)=>{

              let starTime=performance.now();
              let speed=(to-from)/duration;
              let currentValue=from
              //console.log("currentValue",currentValue)

              console.log("performance.now()",performance.now())
              const _run=(t)=>{   
                 //let currentTime=Date.now();
                 const currentTime = performance.now();
                 let difTime=currentTime-starTime;
                 let distance=speed*difTime;
                 let currentValue=from+distance;
                // console.log("currentValue",currentValue)
                 callback(currentValue)
                 if(difTime>=duration){
                    currentValue=to;
                    callback(currentValue)
                    return
                 }
                 // 请求浏览器在下一次重绘之前调用animate函数
                 requestAnimationFrame(_run)
              }
               //手动调用一次函数
              requestAnimationFrame(_run)
         }
         animates(3000,0,100,(value)=>{
             console.log('value',value)
             content=document.getElementById("content").textContent=`当前数值为:${value.toFixed(0)}`
         })


  </script>
</html>