30秒学会 JavaScript 片段 · 2023年4月19日

30秒学会 JavaScript 片段 – What is the difference between synchronous and asynchronous code in JavaScript?

Synchronous code runs in sequence. This means that each operation must wait for the previous one to complete before executing.

代码实现

console.log('One');
console.log('Two');
console.log('Three');
// LOGS: 'One', 'Two', 'Three'

Asynchronous code runs in parallel. This means that an operation can occur while another one is still being processed.

使用样例

console.log('One');
setTimeout(() => console.log('Two'), 100);
console.log('Three');
// LOGS: 'One', 'Three', 'Two'

Asynchronous code execution is often preferable in situations where execution can be blocked indefinitely. Some examples of this are network requests, long-running calculations, file system operations etc. Using asynchronous code in the browser ensures the page remains responsive and the user experience is mostly unaffected.

翻译自:https://www.30secondsofcode.org/js/s/sync-async