The difference between synchronous and asynchronous code in JavaScript

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/

猜你喜欢

转载自blog.csdn.net/wml00000/article/details/88907968
今日推荐