打赏

Promise和setTimeout执行顺序 面试题

1、示例

<!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>Promise和setTimeout执行顺序 面试题</title>
    </head>

    <body>
        <script type="text/javascript">
            setTimeout(function() {
                console.log(1)
            }, 0);
            new Promise(function(a, b) {
                console.log(2);
                for(var i = 0; i < 10; i++) {
                    i == 9 && a();
                }
                console.log(3);
            }).then(function() {
                console.log(4)
            });
            console.log(5)
        </script>
    </body>

</html>

2、解释

最需要 解释的是:then和settimeout执行顺序,即setTimeout(fn, 0)在下一轮“事件循环”开始时执行,Promise.then()在本轮“事件循环”结束时执行。因此then 函数先输出,settimeout后输出。

 3、自测题:

<!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 执行顺序</title>
    </head>

    <body>
        <script src="https://cdn.bootcss.com/lodash.js/4.17.10/lodash.min.js"></script>
        <script type="text/javascript">
            console.log(1)
            setTimeout(function(){
                console.log(2);
                let promise = new Promise(function(resolve, reject) {
                      console.log(7);
                      resolve()
                }).then(function(){
                    console.log(8)
                });
            },1000);
            setTimeout(function(){
                console.log(10);
                let promise = new Promise(function(resolve, reject) {
                      console.log(11);
                      resolve()
                }).then(function(){
                    console.log(12)
                });
            },0);
            let promise = new Promise(function(resolve, reject) {
                  console.log(3);
                  resolve()
            }).then(function(){
                console.log(4)
            }).then(function(){
                console.log(9)
            });
            console.log(5)
        </script>
    </body>

</html>

 

posted @ 2018-03-29 16:32  孟繁贵  阅读(12310)  评论(0编辑  收藏  举报
TOP