Home > Web Front-end > JS Tutorial > body text

What are the ways to implement asynchronousness in javascript?

青灯夜游
Release: 2021-06-07 17:04:48
Original
3095 people have browsed it

Method: 1. Use setTimeout; 2. Use setImmediate; 3. Use requestAnimationFrame; 4. Realize by monitoring the "new Image" loading status; 5. Realize by monitoring the script loading status; 6. Use Message etc.

What are the ways to implement asynchronousness in javascript?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Native javascript way to achieve asynchronous implementation:

1. setTimeout: This is the simplest one

setTimeout( function() {
    console.log(1);
});
console.log(2);
Copy after login

2. setImmediate: a new function added by IE10, specifically used to liberate the ui thread. IE10 and below and other browsers do not support

setImmediate(function(){
    console.log(1);
});
console.log(2);
Copy after login

3. requestAnimationFrame: a new product in the HTML5/CSS3 era, specially used for 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);
Copy after login

4. Monitoring the new Image loading status: by loading an image in the data:image data format and listening to the loading status to achieve asynchronous .

Although some browsers do not support the data:image image data format, they can still trigger their onerror state to achieve asynchronous implementation. However, IE8 and below do not support images in the data:image data format. , onerror is executed synchronously

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);
Copy after login

5. Monitor script loading status

The principle is the same as new Image. Generate a data:text/javascript script and monitor its loading status to implement asynchronously.

Although some browsers do not support scripts with data in the data:text/javascript format, they can still trigger their onerror and onreadystatechange events to achieve asynchronous implementation.

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);
Copy after login

6. Message: HTML5 new skill, implemented by listening to the window.onmessage event, and then postMessage sends the message, triggering the onmessage event to achieve asynchronous

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);
Copy after login

7. Promise: ES6’s new skill, with 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);
Copy after login

For more programming-related knowledge, please visit: Programming Video ! !

The above is the detailed content of What are the ways to implement asynchronousness in javascript?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template