javascript实现异步的方法有哪些


本文摘自PHP中文网,作者青灯夜游,侵删。

方法:1、利用setTimeout;2、利用setImmediate;3、利用requestAnimationFrame;4、通过监听“new Image”加载状态来实现;5、通过监听script加载状态来实现;6、利用Message等等。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

原生javascript实现异步的方式:

1、setTimeout:这个是最简单的

1

2

3

4

setTimeout( function() {

    console.log(1);

});

console.log(2);

2、setImmediate :IE10添加的新功能,专门用于解放ui线程。IE10以下及其他浏览器不支持

1

2

3

4

setImmediate(function(){

    console.log(1);

});

console.log(2);

3、requestAnimationFrame :HTML5/CSS3时代新产物,专门用于动画。低级浏览器不支持

1

2

3

4

5

6

7

8

9

10

11

12

13

14

var asynByAniFrame = (function(){

    var _window = window,

    frame = _window.requestAnimationFrame

            || _window.webkitRequestAnimationFrame

            || _window.mozRequestAnimationFrame

            || _window.oRequestAnimationFrame

            || _window.msRequestAnimationFrame;

    return function( callback ) { frame( callback ) };

})();

 

asynByAniFrame(function(){

    console.log(1);

})

console.log(2);

4、监听new Image加载状态:通过加载一个data:image数据格式的图片,并监听器加载状态实现异步。

  尽管部分浏览器不支持data:image图片数据格式,但仍然可以触发其onerror状态实现异步,但IE8及以下对data:image数据格式的图片,onerror为同步执行

1

2

3

4

5

6

7

8

9

10

11

12

function asynByImg( callback ) {

    var img = new Image();

    img.onload = img.onerror = img.onreadystatechange = function() {

        img = img.onload = img.onerror = img.onreadystatechange = null;

        callback();

    }

    img.src = "data:image/png,";

}

asynByImg(function(){

    console.log(1);

});

console.log(2);

5、监听script加载状态

  原理同new Image是一样的,生成一个data:text/javascript的script,并监听其加载状态实现异步。

  尽管部分浏览器不支持data:text/javascript格式数据的script,但仍然可以触发其onerror、onreadystatechange事件实现异步。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

var asynByScript = (function() {

    var _document = document,

        _body = _document.body,

        _src = "data:text/javascript,",

        //异步队列

        queue = [];

    return function( callback ) {

            var script = _document.createElement("script");

            script.src  = _src;

            //添加到队列

            queue[ queue.length ] = callback;

            script.onload = script.onerror = script.onreadystatechange = function () {

                script.onload = script.onerror = script.onreadystatechange = null;

                _body.removeChild( script );

                script = null;

                //执行并删除队列中的第一个

                queue.shift()();

            };

            _body.appendChild( script );

        }

 

    })();

 

asynByScript( function() {

    console.log(1);

} );

console.log(2);

6、Message:html5新技能,通过监听window.onmessage事件实现,然后postMessage发送消息,触发onmessage事件实现异步

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

var asynByMessage = (function() {

        //异步队列

        var queue = [];

        window.addEventListener('message', function (e) {

            //只响应asynByMessage的召唤

            if ( e.data === 'asynByMessage' ) {

                e.stopPropagation();

                if ( queue.length ) {

                    //执行并删除队列中的第一个

                    queue.shift()();

                }

            }

        }, true);

        return function( callback ) {

            //添加到队列

            queue[ queue.length ] = callback;

            window.postMessage('asynByMessage', '*');

        };

    })();

 

asynByMessage(function() {

    console.log(1);

});

console.log(2);

7、Promise: ES6的新技能,具有异步性质

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

var asynByPromise = (function() {

        var promise = Promise.resolve({

                then : function( callback ) {

                    callback();

                }

            });

        return function( callback ) {

                    promise.then(function(){

                        callback();

                    })

                };

    })();

asynByPromise(function() {

    console.log(1);

});

console.log(2);

更多编程相关知识,请访问:编程视频!!

以上就是javascript实现异步的方法有哪些的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

javascript如何实现页面跳转

javascript代码有几种使用方式

用html和css以及js制作简单的网页菜单界面的代码

javascript怎么删除当前节点

javascript中array什么意思

json.parse()和json.stringify()的性能测试(示例)

javascript的后缀是什么

javascript和typescript的区别是什么

javascript中的json方法有哪些

如何理解javascript中的原型链

更多相关阅读请进入《javascript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...