7 ways native JavaScript implements Asynchrony

Source: Internet
Author: User

Native JavaScript implements Asynchrony in far less than 7 different ways,
Can be divided into 3 categories,
Delay type: settimeout (SetInterval is also available), Requestanimationframe, Setimmediate (IE10 and above)
Type of listener event implementation: Monitor new image load state, monitor script load state, monitor IFRAME loading status, message
With asynchronous function type Promise, Ajax (XMLHttpRequest, ActiveXObject), Worker;
Considering the
1.iframe efficiency is too slow;
2.ajax under IE must load the real file to trigger open and send;
Although the 3.Worker has asynchronous characteristics, but it belongs to the category of multithreading, it is necessary to write the main algorithm in a separate JS file in order to fully reflect its advantages, if only for the purpose of asynchronous use is too wasteful.
All of these 3 ways are not listed.


one, the way to achieve asynchronous

1.setTimeout
2.setImmediate
3.requestAnimationFrame
4. Monitor new image Loading status
5. Monitor script load Status
6.Message
7.Promise


settimeout

This is the simplest.

settimeout (function () {
    console.log (1);
});
Console.log (2);



setimmediate

IE10 adds new features that are specifically designed to liberate the UI thread. IE10 below and other browsers are not supported

Setimmediate (function () {
    console.log (1);
});
Console.log (2);



Requestanimationframe

A new product of the HTML5/CSS3 era, devoted to animation. Low-level browsers do not support

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);



Monitor New Image load State implementation

Asynchronously by loading a picture in a Data:image data format and the listener loading state.

Although some browsers do not support Data:image image Data format, but can still trigger its onerror state implementation asynchronous, but IE8 and the following Data:image data format of the picture, onerror for synchronous execution

function Asynbyimg (callback) {
    var img = new Image ();
    Img.onload = Img.onerror = Img.onreadystatechange = function () {
        img = img.onload = Img.onerror = Img.onreadystatechan GE = null;
        Callback (); 
    }
    IMG.SRC = "Data:image/png,";
}
Asynbyimg (function () {
    console.log (1);
});
Console.log (2);



Monitor script load State implementation

The principle is the same as new image, which generates a Data:text/javascript script and listens to its loading state for asynchronous implementation.

Although some browsers do not support script for data:text/javascript format data, they can still trigger their onerror, onreadystatechange events to implement Asynchrony.

var Asynbyscript = (function () {
    var _document = document,
        _body = _document.body,
        _src = "Data:text/javascri PT, ",
        //asynchronous queue
        \ = [];
    return function (callback) {
            var script = _document.createelement ("script");
            Script.src  = _src;
            Add to queue
            queue[queue.length] = callback;
            Script.onload = Script.onerror = Script.onreadystatechange = function () {
                script.onload = Script.onerror = Script.on ReadyStateChange = null;
                _body.removechild (script);
                script = null;
                Executes and deletes the first
                Queue.shift () ()
            in the queue; _body.appendchild (script);
        }

    }) ();

Asynbyscript (function () {
    console.log (1);
});
Console.log (2);



Message

HTML5 new skills by listening to Window.onmessage event implementations, then PostMessage sending messages, triggering OnMessage events to implement asynchronous

var asynbymessage = (function () {
        //asynchronous queues
        var queue = [];
        Window.addeventlistener (' message ', function (e) {
            ///response only to Asynbymessage call
            if (e.data = = ' Asynbymessage ') {
                e.stoppropagation ();
                if (queue.length) {
                    //executes and deletes the first
                    Queue.shift () ();}}}
        , True,
        in the queue; return function (callback) {
            //Add to Queue
            queue[queue.length] = callback;
            Window.postmessage (' asynbymessage ', ' * ');
        }
    ();

Asynbymessage (function () {
    console.log (1);
});
Console.log (2);



Promise

ES6 's new skills, with an asynchronous nature

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);



Ii. operating efficiency of various asynchronous methods

Test code

/** * Check if a method is browser native * @param {Function} func the method to be detected * @return {Boolean} whether the browser native/Function Isnativefunc (func

{return typeof func = = ' function ' &&/^[^{]+\{\s*\[native \w/.test (func);} var _window = window, frame = _window.requestanimationframe | | _window.webkitrequestanimationframe | | _window.mozrequestanimationframe | | _window.orequestanimationframe | |
    _window.msrequestanimationframe;

_window = null; var asynbypromise = isnativefunc (window.
                    Promise) && (function () {var Promise = Promise.resolve ({then:function (callback) {
                Callback ();
        }
            });
                    return function (callback) {Promise.then (function () {callback ();
    })
                };

})();

var asynbyaniframe = Isnativefunc (frame) && function (callback) {frame (callback);};var Asynbyworker = (function () {//Generate a new thread var worker = (' asynworker.js '), queue = [];
    Listener thread Worker.addeventlistener (' message ', function (e) {//Processing result Queue.shift () ();
    }, True); 
        return function (callback) {queue[queue.length] = callback;
    Worker.postmessage (");
};

})();
        var asynbymessage = Isnativefunc (window.postmessage) && (function () {//asynchronous queues var queue = []; Window.addeventlistener (' message ', function (e) {///response only to Asynbymessage call if (E.data = = ' Asy
                Nbymessage ') {e.stoppropagation ();
                if (queue.length) {//execute and delete the first queue.shift () () in the queue;
        }}, True);
            return function (callback) {//Add to queue queue[queue.length] = callback;
        Window.postmessage (' asynbymessage ', ' * ');
    };

})(); functionAsynbyimg (callback) {var img = new Image (); Img.onload = Img.onerror = Img.onreadystatechange = function () {img = Img.onload = Img.onerror = Img.onreadystate
        change = NULL; 
    Callback ();

} img.src = "Data:image/png,";}
Whether to support picture asynchronous mode var supasynimg = true;

Asynbyimg (function () {//IE8 and the following picture for the Data:image data format, onerror for synchronous execution supasynimg = false;}) var Asynbyscript = (function () {var _document = document, _body = _document.body, _src = "data:text/j

    Avascript, ",//asynchronous queue \ = [];
            return function (callback) {var script = _document.createelement ("script");
            SCRIPT.SRC = _SRC;
            Add to queue queue[queue.length] = callback; Script.onload = Script.onerror = Script.onreadystatechange = function () {script.onload = Script.onerror
                = Script.onreadystatechange = null;
                _body.removechild (script);
      script = null;          Executes and deletes the first Queue.shift () () in the queue;
            };
        _body.appendchild (script);

}

    })();

function Asynbysetimmediate (callback) {setimmediate (callback);}

settimeout (function () {console.log (' settimeout ');});
    if (supasynimg) {asynbyimg (function () {console.log (' asynbyimg ');    
});
} asynbyscript (function () {console.log (' Asynbyscript ');}); 
    if (Isnativefunc (window.setimmediate)) {asynbysetimmediate (function () {console.log (' asynbysetimmediate ');
}); } if (Isnativefunc window.   
    Promise)) {asynbypromise (function () {console.log (' asynbypromise ');
});
    } if (Isnativefunc (frame)) {Asynbyaniframe (function () {console.log (' asynbyaniframe ');
});
    } if (Isnativefunc (window.postmessage)) {asynbymessage (function () {console.log (' asynbymessage ');
});
    } asynbyworker (function () {console.log (' asynbyworker '); });

In that case, it would be enough to leave 4 in the end.
Advanced Browser
Asynbypromise the fastest when supporting promise.
Support Requestanimationframe slower than promise, faster than others
Other browsers
Support Data:image Data Format picture asynchronous, asynbyimg faster than Asynscript
Each browser supports asynchronous way of DATA:TEXT/JAVASCRIPT data format
So
Asynbypromise > Asynbyaniframe > Asynbyimg > Asynbyscript

Strangely, ie Setimmediate never beat settimeout.



Third, the final code

/** * Check if a method is browser native * @param {Function} func the method to be detected * @return {Boolean} whether the browser native/Function Isnativefunc (func {return typeof func = = ' function ' &&/^[^{]+\{\s*\[native \w/.test (func);} var _window = window, f Rame = _window.requestanimationframe | | _window.webkitrequestanimationframe | | _window.mozrequestanimationframe | | _window.orequestanimationframe | |
    _window.msrequestanimationframe,//Whether support picture asynchronous way supasynimg = true;
_window = null;
    function Asynbyimg (callback) {var img = new Image (); Img.onload = Img.onerror = Img.onreadystatechange = function () {img = Img.onload = Img.onerror = Img.onreadystate
        change = NULL; 
    Callback ();
} img.src = "Data:image/png,";}
Asynbyimg (function () {//IE8 and the following picture for data:image data format, onerror for synchronous execution supasynimg = false;}); var asynfire =//Browser has promise method and is native isnativefunc (window. 
    Promise) &&    (function () {var promise = Promise.resolve ({then:function (callback) {
                    Callback ();
            }
                });
                        return function (callback) {Promise.then (function () {callback ();
        })
                    };
        })()
        ||
            There are requestanimationframe methods in the browser and native Isnativefunc (frame) && function (callback) {
        Frame (callback);
        }
        ||
        Support picture asynchronous supasynimg && Asynbyimg | |
                Script Async (function () {var _document = document, _body = _document.body,
        _SRC = "Data:text/javascript,",//asynchronous queue \ = [];
                return function (callback) {var script = _document.createelement ("script"); Script.src = _src;
                Add to queue queue[queue.length] = callback; Script.onload = Script.onerror = Script.onreadystatechange = function () {script.onload = Script.oner
                    ROR = Script.onreadystatechange = null;
                    _body.removechild (script);
                    script = null;
                Executes and deletes the first Queue.shift () () in the queue;
                };
            _body.appendchild (script);
}
        })(); if (Asynfire!== asynbyimg) {asynbyimg = null;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.