HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

What is the difference between synchronous and asynchronous code in JavaScript?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptsynchronouswhatandbetweendifferencetheasynchronouscode

Problem

Synchronous code runs in sequence. This means that each operation must wait for the previous one to complete before executing.
Asynchronous code runs in parallel. This means that an operation can occur while another one is still being processed.
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.
@Further reading

Solution

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


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.
@Further reading

Code Snippets

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

Context

From 30-seconds-of-code: sync-async

Revisions (0)

No revisions yet.