What is Synchronous JavaScript?
- It means the operations are performed one after the other. So, each line of code should wait for the previous one to finish before proceeding to the next.
- JavaScript is a single-threaded and synchronous language by default
console.log("Start");
console.log("Middle");
console.log("End");
Start
Middle
End
Disadvantages of Synchronous:
- Blocking Execution (Each task must finish before the next starts)
- Slower Performance ( long task delays the entire program)
- UI becomes unresponsive
What is Asynchronous JavaScript?
- It allows multiple tasks to run independently.
- Whenever a task is initiated and while waiting for it to complete, other tasks can proceed. This results in a non-blocking nature and improves performance.
<script>
console.log("Start");
setTimeout(()=>{
console.log("Async Task");
},2000);
console.log("End");
</script>
Start
End
Async Task
How Asynchronous JavaScript works:
To understand the behavior better, it's important to know about the JS environment.
Call Stack
Web API's in Browser
Callback Queue
Event Loop
Call Stack:
- This is where the functions are executed in the order they are called.
- function is added to the stack and executed before moving to the next
Web API(Browser):
- functions like setTimeout, HTTP requests, and event listeners are handled by these browser API
- When an Asynchronous function like setTimeout is called, it is passed to the browser, which manages the timing without blocking the main call stack
Callback Queue
- Once the Web API has finished its job (like waiting for the timeout), it pushes the callback function (like the one in setTimeout) to the callback queue
Event Loop
- It checks the call stack to see if it's empty and pushes the function from the callback queue to the stack for execution.
Several methods that can be used to perform asynchronous JavaScript tasks are listed below:
- setTimeout
- callback
- promises
What is setTimeout:
- This function is used to delay the execution of the code, and this method executes a function after waiting for a specified number of milliseconds
setTimeout(function,delay)
console.log("Start");
setTimeout(()=>{
console.log("Hello after 2 seconds");
},2000);
console.log("End");
Start
End
Hello after 2 seconds
Disadvantages of setTimeout:
- Delay is minimum time, not guaranteed
- Delay depends on the system, which may be execution
- When nested callbacks happen, it results in callback Hell, which makes the code hard to read
What is Promise function:
- It is useful for handling asynchronous operations like API calls, file loading, or time delays more easily.
It has three states:
- Pending- The task in the initial state
- Fulfilled- The task was completed successfully, and the result is available
- Rejected - The task failed, an error is provided
let promise= new Promise(resolve,reject)=>{
//Perform async operation
if(operationSuccessful){
resolve("Task Successfull");
}else{
reject("Task failed");
}
});
Note: The "resolve" and "reject" are not keywords. You can use any name that you want to give to a function
function myPromise(){
return new Promise((res,rej)=>{
let movieTicket=true;
if(movieTicket)
res(350)
else
rej()
})
}
myPromise().then((amt)=>console.log(`Enjoy the movie, I have sent ${amt}`))
myPromise().catch(()=>console.log("Sorry! Try to book for another movie")
O/P:
Enjoy the movie, I have sent 350
Top comments (0)