打赏

js 实现sleep函数

1.sleep函数

sleep函数作用是让线程休眠,等到指定时间在重新唤起。

2、sleep实现

<!DOCTYPE html>
<html lang="zh">

    <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>js sleep函数</title>
    </head>

    <body>
        <script type="text/javascript">
            //方法一
            function sleep1(ms, callback) {
                setTimeout(callback, ms)
            }
            //sleep 1s
            sleep1(1000, () => {
                console.log(1000)
            })
            //方法二
            function sleep2(ms) {
                return new Promise(function(resolve, reject) {
                    setTimeout(resolve, ms)
                })
            }
            sleep2(1000).then(() => {
                console.log(2000)
            })
            //方法三
            function sleep3(ms) {
                return new Promise(function(resolve, reject) {
                    setTimeout(resolve, ms)
                })
            }
            async function init() {
                await sleep3(1000);
            }
            init().then(() => {
                console.log(3000)
            })
        </script>
    </body>

</html>

 

posted @ 2018-10-10 11:08  孟繁贵  阅读(17852)  评论(0编辑  收藏  举报
TOP