欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

关于promise的一个demo

程序员文章站 2022-04-24 10:51:53
...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .balls {
            width: 60px;
            height: 60px;
            border-radius: 50%;
        }

        .ball1 {
            background-color: red;
        }

        .ball2 {
            background-color: yellow;
        }

        .ball3 {
            background-color: blue;
        }
    </style>
</head>
<body>
<div>
    <div class="ball1 balls" style="margin-left: 0"></div>
    <div class="ball2 balls" style="margin-left: 0"></div>
    <div class="ball3 balls" style="margin-left: 0"></div>
</div>
<script>
    let ball1 = document.querySelector('.ball1');
    let ball2 = document.querySelector('.ball2');
    let ball3 = document.querySelector('.ball3');

    function yanking(dom, distance) {
        return new Promise(resolve => {
            let s = setInterval(function () {
                let left = parseInt(dom.style.marginLeft, 10);
                if (left < distance) {
                    dom.style.marginLeft = ++left + 'px';
                } else if (left > distance) {
                    dom.style.marginLeft = --left + 'px';
                } else {
                    clearInterval(s);
                    resolve(dom);
                }
            }, 5);
        });
    }

    yanking(ball1, 100)
        .then(() => {
            return yanking(ball2, 200);
        })
        .then(() => {
            return yanking(ball3, 300);
        })
        .then(() => {
            return yanking(ball3, 150);
        })
        .then(() => {
            return yanking(ball2, 150);
        })
        .then(() => {
            return yanking(ball1, 150);
        });
</script>
</body>
</html>
复制代码