(精华)2020年6月28日 Canvas 进度条

<!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>进度条</title>
    <style>
        .my-progress {
            width: 200px;
            background: red;
            font-size: 12px;
            width: 0;
            height: 10px;
            line-height: 20px;
            border-radius: 20px;
        }
    </style>
</head>

<body>
    <div id="myDiv" class="my-progress" style="width:0"></div>
    <div id="percent">0%</div>
    <button id="btn">run</button>
    <script>
        var timer;
        //第一种requestAnimationFrame
        btn.onclick = function () {
            myDiv.style.width = '0';
            cancelAnimationFrame(timer); //清楚定时器
            var fun = function () {
                if (parseInt(myDiv.style.width) < 200) {
                    myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';
                    percent.innerHTML = parseInt(myDiv.style.width) / 5 + '%';
                    timer = requestAnimationFrame(fun);
                } else {
                    cancelAnimationFrame(timer); //清楚定时器
                }
            }
            timer = requestAnimationFrame(fun);
            // 由系统来决定回调函数的执行时机,不会有丢帧,卡顿的问题
            // cpu节能
            // 函数节流
            // 兼容性:不同的浏览器需要加前缀
        }
        //第二种setInterval
        btn.onclick = function () {
            clearInterval(timer);
            myDiv.style.width = '0';
            timer = setInterval(function () {
                if (parseInt(myDiv.style.width) < 500) {
                    myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';
                    myDiv.innerHTML = parseInt(myDiv.style.width) / 5 + '%';
                } else {
                    clearInterval(timer);
                }
            }, 16);
        }
        //第三种setTimeout
        btn.onclick = function () {
            clearTimeout(timer);
            myDiv.style.width = '0';
            timer = setTimeout(function fn() {
                if (parseInt(myDiv.style.width) < 200) {
                    myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';
                    myDiv.innerHTML = parseInt(myDiv.style.width) / 5 + '%';
                    timer = setTimeout(fn, 16);
                } else {
                    clearTimeout(timer);
                }
            }, 16);
        }
    </script>
</body>

</html>

你可能感兴趣的:(#,canvas,canvas)