Synchronous :
- operations are performed one after another in sequence.
- each line code wait for the previous one to finish before proceeding to the next one . example:
console.log("Hi");
console.log("Bye");
console.log("How are you?");
output:
Hi
Bye
How are you?
Drawbacks:
- when dealing with time-consuming tasks like fetching data from a server or reading a large file. If such a task is included in the sequence, it will block the execution of the rest of the code until it’s finished, leading to potential delays and a bad user experience.
Asynchronous:
allows multiple taks to run independently of each other.
a task can be initiated and while waiting for it to complete other task can proceed.
Example:
console.log("Hi");
setTimeout(() => {
console.log("welcome");
}, 2000);
console.log("End");
output:
Hi
welcome
End
Advantage:
This non-blocking nature helps improve performance and responsiveness, especially in web applications.
When Asynchronous happened?
Javascript by default runs synchronous .it executes one line after another on a single thread.
But asynchronous behavior happens only when we use special functions or APIs that don’t block the main thread. These functions are provided by the browser (Web APIs) or Node.js APIs, not by JavaScript itself.Timers:
setTimeout, setInterval
Browser Events:
e.g., onclick, onkeyup, addEventListener
HTTP Requests / Fetch API:
fetch(), XMLHttpRequest
Promises:
Anything returning a promise (fetch, custom promise, async/await)
Top comments (0)