javascript
The difference between synchronous and asynchronous code in JavaScript
文章目錄
- Answer
- Good to hear
- 參考鏈接
Answer
Synchronous means each operation must wait for the previous one to complete.
Asynchronous means an operation can occur while another operation is still being processed.
In JavaScript, all code is synchronous due to the single-threaded nature of it. However, asynchronous operations not part of the program (such as XMLHttpRequest or setTimeout) are processed outside of the main thread because they are controlled by native code (browser APIs), but callbacks part of the program will still be executed synchronously.
同步執行意味著必須等前面的代碼執行完畢之后,后面的才可以執行。也就是順序執行,只沿著一條路走。
異步執行意味著可以在另一個操作執行的過程中同時執行其他操作,也就是本來沿著一條路,后來分叉了變成兩條路。
console.log("主干道"); setTimeout(function(){console.log("異步執行:支線1")},500); console.log("異步執行:支線2");執行結果
主干道 異步執行:支線2 異步執行:支線1
在JavaScript中,由于其本身單線程的原因,所有的代碼都是同步執行的。之所以有異步操作這種現象(XHR請求、定時器),是瀏覽器API給它的,瀏覽器(JavaScript解釋器)本身是支持多線程的。瀏覽器(JavaScript解釋器)幫助JavaScript調度線程,JavaScript內部只有一個主線程,當要執行回調時,瀏覽器幫著把回調方法放到主線程中。
Good to hear
- JavaScript has a concurrency model based on an “event loop”.
- Functions like alert block the main thread so that no user input is registered until the user closes it.
JavaScript具有基于“事件循環”的并發模型。
參考鏈接
https://30secondsofknowledge.com/
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的The difference between synchronous and asynchronous code in JavaScript的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于ArcGIS API for Jav
- 下一篇: 基于ArcGIS API for Jav