首頁 > web前端 > js教程 > 主體

javascript實作異步的方法有哪些

青灯夜游
發布: 2021-06-07 17:04:48
原創
2960 人瀏覽過

方法:1、利用setTimeout;2、利用setImmediate;3、利用requestAnimationFrame;4、透過監聽「new Image」載入狀態來實現;5、透過監聽script載入狀態來實現;6、利用Message等等。

javascript實作異步的方法有哪些

本教學操作環境:windows7系統、javascript1.8.5版、Dell G3電腦。

原生javascript實作非同步的方式:

#1、setTimeout:這個是最簡單的

setTimeout( function() {
    console.log(1);
});
console.log(2);
登入後複製

2、setImmediate :IE10新增的功能,專門用於解放ui執行緒。 IE10以下及其他瀏覽器不支援

setImmediate(function(){
    console.log(1);
});
console.log(2);
登入後複製

#3、requestAnimationFrame :HTML5/CSS3時代新產物,專門用於動畫。低階瀏覽器不支援

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為同步執行

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事件實現非同步。

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事件實現異步

#
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 的新技能,具有非同步性質

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實作異步的方法有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!