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.
同步執(zhí)行意味著必須等前面的代碼執(zhí)行完畢之后,后面的才可以執(zhí)行。也就是順序執(zhí)行,只沿著一條路走。
異步執(zhí)行意味著可以在另一個(gè)操作執(zhí)行的過程中同時(shí)執(zhí)行其他操作,也就是本來沿著一條路,后來分叉了變成兩條路。
console.log("主干道"); setTimeout(function(){console.log("異步執(zhí)行:支線1")},500); console.log("異步執(zhí)行:支線2");執(zhí)行結(jié)果
主干道 異步執(zhí)行:支線2 異步執(zhí)行:支線1
在JavaScript中,由于其本身單線程的原因,所有的代碼都是同步執(zhí)行的。之所以有異步操作這種現(xiàn)象(XHR請求、定時(shí)器),是瀏覽器API給它的,瀏覽器(JavaScript解釋器)本身是支持多線程的。瀏覽器(JavaScript解釋器)幫助JavaScript調(diào)度線程,JavaScript內(nèi)部只有一個(gè)主線程,當(dāng)要執(zhí)行回調(diào)時(shí),瀏覽器幫著把回調(diào)方法放到主線程中。
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具有基于“事件循環(huán)”的并發(fā)模型。
參考鏈接
https://30secondsofknowledge.com/
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的The difference between synchronous and asynchronous code in JavaScript的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于ArcGIS API for Jav
- 下一篇: 基于ArcGIS API for Jav