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

About JavaScript synchronous and asynchronous programming examples usage

伊谢尔伦
Release: 2017-06-16 10:20:01
Original
2111 people have browsed it

If you want to learn javascript in depth, take a look at the following article, it may be helpful to you.

Preface

If you are interested in becoming an excellent front-end engineer, or want to learn JavaScript in depth, asynchronous programming is an essential knowledge point, and it is also what distinguishes beginners , one of the basis for intermediate or advanced front-end. If you don’t have a clear concept of asynchronous programming, then I suggest you spend some time learning JavaScript asynchronous programming. If you have your own unique understanding of asynchronous programming, you are welcome to read this article and communicate together.

Synchronization and Asynchrony

Before introducing asynchronous, let’s review that the so-called synchronous programming means that the computer executes code in sequence line by line. The time-consuming execution of the current code task will block the execution of subsequent code.

Synchronous programming is a typical request-response model. When a request calls a function or method, it needs to wait for its response to return, and then execute subsequent code.

Under normal circumstances, synchronous programming, where the code is executed in order, can well ensure the execution of the program. However, in some scenarios, such as reading file contents or requesting server interface data, Subsequent operations need to be performed based on the content of the returned data. The process of reading the file and requesting the interface until the data is returned takes time. The worse the network, the longer it takes. If it is implemented according to synchronous programming, the time spent waiting for the data to be returned , JavaScript cannot handle other tasks. At this time, any operations such as page interaction and scrolling will also be blocked. This is obviously extremely unfriendly and unacceptable. This is exactly the scenario where asynchronous programming needs to show its talents, as shown below, Time-consuming task A will block the execution of task B, and wait until task A is completed before continuing to execute B:

About JavaScript synchronous and asynchronous programming examples usage

When using asynchronous programming, wait for the response of the current task to return before returning , you can continue to execute subsequent code, that is, the current execution task will not block subsequent execution.

Asynchronous programming is different from the request-response mode of synchronous programming. It is a kind of event-driven programming. After requesting to call a function or method, there is no need to wait for the response immediately and you can continue to perform other tasks before. After the task response returns, the caller can be notified through status, notifications and callbacks.

Multi-threading

As explained before, asynchronous programming can effectively solve the problem of synchronous programming blocking, so what are the ways to implement asynchronous programming? Usually the way to implement asynchronous is multi-threading, such as C#, that is, multiple threads are started at the same time, and different operations can be executed in parallel. As shown in the figure below, while time-consuming task A is executed, task B can also be executed in thread two:

About JavaScript synchronous and asynchronous programming examples usage

JavaScript single thread

The JavaScript language execution environment is single-threaded. When a single thread executes a program, the program paths taken by a single thread are arranged in consecutive order, and the previous ones must be processed. Well, the later ones will be executed, and when using asynchronous implementation, multiple tasks can be executed concurrently. So how to implement asynchronous programming in JavaScript? The next section will elaborate on its asynchronous mechanism.

Parallel and Concurrency

As mentioned earlier, multi-threaded tasks can be executed in parallel, and JavaScript single-threaded asynchronous programming can achieve concurrent execution of multi-tasks. It is necessary to explain the difference between parallelism and concurrency.

  • Parallel refers to multiple tasks being performed at the same time;

  • Concurrency refers to multiple tasks being performed at the same time within the same time period. But at a certain moment, only a certain task is executed;

The number of concurrent connections usually refers to the number of times the browser initiates a request to the server and establishes a TCP connection, and the server establishes it per second The total number of connections, and if the server can handle one connection in 10ms, then the number of concurrent connections is 100.

JavaScript asynchronous mechanism

This section introduces the JavaScript asynchronous mechanism. First, let’s look at an example:

    for (var i = 0; i < 5; i ++) {
        setTimeout(function(){
            console.log(i);
        }, 0);
    }
    console.log(i);
    //5 ; 5 ; 5 ; 5; 5
Copy after login

You should understand that the final output is all 5:

  1. i here is the variable of the context where the for loop is located, and there is only one i;

  2. i==5 at the end of the loop;

  3. JavaScript single-threaded event handler will not execute the next event until the thread is idle.

As mentioned in the third point above, if you want to truly understand setTimeout() in the above example and the JavaScript asynchronous mechanism, you need to understand the JavaScript event loop and concurrency model.

Concurrency model

Currently, we already know that when JavaScript performs an asynchronous task, it does not need to wait for the response to return, and can continue to perform other tasks, and when the response returns, you will get Notification, execution callback or event handler. So how exactly is all this done, and in what rules or order does it work? Next we need to answer this question.

Note: There is essentially no difference between callbacks and event handlers, they are just called differently in different situations.

As mentioned earlier, JavaScript asynchronous programming allows multiple tasks to be executed concurrently, and the basis for realizing this function is that JavScript has a concurrency model based on the event loop.

Stack and Queue

Before introducing the JavaScript concurrency model, let’s briefly introduce the difference between the stack and the queue:

  • Heap: a certain location in memory An unblocked area, usually storing objects (reference types);

  • Stack: a data structure stored in last-in-first-out order, usually storing function parameters and basic type value variables (Access by value);

  • Queue (queue): data structure stored in first-in, first-out order.

Event Loop

The JavaScript engine is responsible for parsing and executing JavaScript code, but it cannot run alone. It usually requires a host environment, usually such as Browser or Node server, the single thread mentioned above refers to the creation of a single thread in these host environments, providing a mechanism to call the JavaScript engine to complete the scheduling and execution of multiple JavaScript code blocks (yes, JavaScript codes are all in blocks (executed), this mechanism is called event loop (Event Loop).

注:这里的事件与DOM事件不要混淆,可以说这里的事件包括DOM事件,所有异步操作都是一个事件,诸如ajax请求就可以看作一个request请求事件。

JavaScript执行环境中存在的两个结构需要了解:

  • 消息队列(message queue),也叫任务队列(task queue):存储待处理消息及对应的回调函数或事件处理程序;

  • 执行栈(execution context stack),也可以叫执行上下文栈:JavaScript执行栈,顾名思义,是由执行上下文组成,当函数调用时,创建并插入一个执行上下文,通常称为执行栈帧(frame),存储着函数参数和局部变量,当该函数执行结束时,弹出该执行栈帧;

注:关于全局代码,由于所有的代码都是在全局上下文执行,所以执行栈顶总是全局上下文就很容易理解,直到所有代码执行完毕,全局上下文退出执行栈,栈清空了;也即是全局上下文是第一个入栈,最后一个出栈。

任务

分析事件循环流程前,先阐述两个概念,有助于理解事件循环:同步任务和异步任务。

任务很好理解,JavaScript代码执行就是在完成任务,所谓任务就是一个函数或一个代码块,通常以功能或目的划分,比如完成一次加法计算,完成一次ajax请求;很自然的就分为同步任务和异步任务。同步任务是连续的,阻塞的;而异步任务则是不连续,非阻塞的,包含异步事件及其回调,当我们谈及执行异步任务时,通常指执行其回调函数。

事件循环流程

关于事件循环流程分解如下:

  1. 宿主环境为JavaScript创建线程时,会创建堆(heap)和栈(stack),堆内存储JavaScript对象,栈内存储执行上下文;

  2. 栈内执行上下文的同步任务按序执行,执行完即退栈,而当异步任务执行时,该异步任务进入等待状态(不入栈),同时通知线程:当触发该事件时(或该异步操作响应返回时),需向消息队列插入一个事件消息;

  3. 当事件触发或响应返回时,线程向消息队列插入该事件消息(包含事件及回调);

  4. 当栈内同步任务执行完毕后,线程从消息队列取出一个事件消息,其对应异步任务(函数)入栈,执行回调函数,如果未绑定回调,这个消息会被丢弃,执行完任务后退栈;

  5. 当线程空闲(即执行栈清空)时继续拉取消息队列下一轮消息(next tick,事件循环流转一次称为一次tick)。

使用代码可以描述如下:

    var eventLoop = [];    var event;    var i = eventLoop.length - 1; // 后进先出

    while(eventLoop[i]) {        event = eventLoop[i--]; 
        if (event) { // 事件回调存在
            event();
        }        // 否则事件消息被丢弃
    }
Copy after login

这里注意的一点是等待下一个事件消息的过程是同步的。

并发模型与事件循环
    var ele = document.querySelector(&#39;body&#39;);    function clickCb(event) {        console.log(&#39;clicked&#39;);
    }    function bindEvent(callback) {
        ele.addEventListener(&#39;click&#39;, callback);
    }    

    bindEvent(clickCb);
Copy after login

针对如上代码我们可以构建如下并发模型:

About JavaScript synchronous and asynchronous programming examples usage

如上图,当执行栈同步代码块依次执行完直到遇见异步任务时,异步任务进入等待状态,通知线程,异步事件触发时,往消息队列插入一条事件消息;而当执行栈后续同步代码执行完后,读取消息队列,得到一条消息,然后将该消息对应的异步任务入栈,执行回调函数;一次事件循环就完成了,也即处理了一个异步任务。

再谈About JavaScript synchronous and asynchronous programming examples usage

了解了JavaScript事件循环后我们再看前文关于About JavaScript synchronous and asynchronous programming examples usage的例子就比较清晰了:

About JavaScript synchronous and asynchronous programming examples usage所表达的意思是:等待0秒后(这个时间由第二个参数值确定),往消息队列插入一条定时器事件消息,并将其第一个参数作为回调函数;而当执行栈内同步任务执行完毕时,线程从消息队列读取消息,将该异步任务入栈,执行;线程空闲时再次从消息队列读取消息。

再看一个实例:

    var start = +new Date();    var arr = [];

    setTimeout(function(){        console.log(&#39;time: &#39; + (new Date().getTime() - start));
    },10);    for(var i=0;i<=1000000;i++){
        arr.push(i);
    }
Copy after login

执行多次输出如下:

About JavaScript synchronous and asynchronous programming examples usage

setTimeout异步回调函数里我们输出了异步任务注册到执行的时间,发现并不等于我们指定的时间,而且两次时间间隔也都不同,考虑以下两点:

  • 在读取消息队列的消息时,得等同步任务完成,这个是需要耗费时间的;

  • 消息队列先进先出原则,读取此异步事件消息之前,可能还存在其他消息,执行也需要耗时;

所以异步执行时间不精确是必然的,所以我们有必要明白无论是同步任务还是异步任务,都不应该耗时太长,当一个消息耗时太长时,应该尽可能的将其分割成多个消息。

Web Workers

每个Web Worker或一个跨域的iframe都有各自的堆栈和消息队列,这些不同的文档只能通过postMessage方法进行通信,当一方监听了message事件后,另一方才能通过该方法向其发送消息,这个message事件也是异步的,当一方接收到另一方通过postMessage方法发送来的消息后,会向自己的消息队列插入一条消息,而后续的并发流程依然如上文所述。

JavaScript异步实现

关于JavaScript的异步实现,以前有:回调函数,发布订阅模式,Promise三类,而在ES6中提出了生成器(Generator)方式实现,关于回调函数和发布订阅模式实现可参见另一篇文章,后续将推出一篇详细介绍Promise和Generator。

以上就是javascript同步与异步的全部内容了,感谢大家的阅读。About JavaScript synchronous and asynchronous programming examples usage


The above is the detailed content of About JavaScript synchronous and asynchronous programming examples usage. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!