If you want to learn javascript in depth, take a look at the following article, it may be helpful to you. PrefaceIf 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 AsynchronyBefore 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.
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: 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.
Multi-threadingAs 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: JavaScript single threadThe 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 ConcurrencyAs 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.
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 mechanismThis 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:
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 modelCurrently, 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 QueueBefore introducing the JavaScript concurrency model, let’s briefly introduce the difference between the stack and the queue:
Event LoopThe 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执行环境中存在的两个结构需要了解:
注:关于全局代码,由于所有的代码都是在全局上下文执行,所以执行栈顶总是全局上下文就很容易理解,直到所有代码执行完毕,全局上下文退出执行栈,栈清空了;也即是全局上下文是第一个入栈,最后一个出栈。 任务分析事件循环流程前,先阐述两个概念,有助于理解事件循环:同步任务和异步任务。 任务很好理解,JavaScript代码执行就是在完成任务,所谓任务就是一个函数或一个代码块,通常以功能或目的划分,比如完成一次加法计算,完成一次ajax请求;很自然的就分为同步任务和异步任务。同步任务是连续的,阻塞的;而异步任务则是不连续,非阻塞的,包含异步事件及其回调,当我们谈及执行异步任务时,通常指执行其回调函数。 事件循环流程关于事件循环流程分解如下:
使用代码可以描述如下: 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('body'); function clickCb(event) { console.log('clicked'); } function bindEvent(callback) { ele.addEventListener('click', callback); } bindEvent(clickCb); Copy after login 针对如上代码我们可以构建如下并发模型: 如上图,当执行栈同步代码块依次执行完直到遇见异步任务时,异步任务进入等待状态,通知线程,异步事件触发时,往消息队列插入一条事件消息;而当执行栈后续同步代码执行完后,读取消息队列,得到一条消息,然后将该消息对应的异步任务入栈,执行回调函数;一次事件循环就完成了,也即处理了一个异步任务。 再谈About JavaScript synchronous and asynchronous programming examples usage了解了JavaScript事件循环后我们再看前文关于
再看一个实例: var start = +new Date(); var arr = []; setTimeout(function(){ console.log('time: ' + (new Date().getTime() - start)); },10); for(var i=0;i<=1000000;i++){ arr.push(i); } Copy after login 执行多次输出如下: 在
所以异步执行时间不精确是必然的,所以我们有必要明白无论是同步任务还是异步任务,都不应该耗时太长,当一个消息耗时太长时,应该尽可能的将其分割成多个消息。 Web Workers每个Web Worker或一个跨域的iframe都有各自的堆栈和消息队列,这些不同的文档只能通过postMessage方法进行通信,当一方监听了message事件后,另一方才能通过该方法向其发送消息,这个message事件也是异步的,当一方接收到另一方通过postMessage方法发送来的消息后,会向自己的消息队列插入一条消息,而后续的并发流程依然如上文所述。 JavaScript异步实现关于JavaScript的异步实现,以前有:回调函数,发布订阅模式,Promise三类,而在ES6中提出了生成器(Generator)方式实现,关于回调函数和发布订阅模式实现可参见另一篇文章,后续将推出一篇详细介绍Promise和Generator。 以上就是javascript同步与异步的全部内容了,感谢大家的阅读。 |
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!