Asynchronous Javascript
Hello devs , in Today’s Topic we will cover Asynchronous Programming with Javascript .
So there are essentials technical terms which you will need to remember, specially if you are dealing with interview’s question related to Asynchrouns javascript .
1-Topics To Cover :
- Timeouts and Intervals
- callbacks
- Promises
- Async Await
- Event loop
2-Introduction :
So the main three questions which we should ask are :
- What and Why of Async Javascript ?
- What we mean by Timeouts , Intervals , Callback , Promises and Async await ?
- How all of them behave with respect to the event loop ?
A-Async Javascript — What and Why ?
the first point to understand about javascript is that in it’s most basic form ,Javascrpt is Synchronous ,blocking and single threaded language
- Javascript is Synchronous :
function a() {
console.log("a")
}
function b() {
console.log("b")
}code execute top down with only one line beeing executing at any given time
- Javascript is Blocking :
because of it’s synchronous nature , no matter how the previous process takes , the subsequent won’t kick off until the former is complited
for example , sometime our browser appears to be frozen , that’s because the app is executing an intenssive chunk of code without returning the control to the browser . this is blocking , browser is blocked from handling usrs’s input and perform other tasks
- Javascript is Single threaded :
a Thread is simply s process used by your javascript code to run a task , and each thread can do one task at each time .
there are other languages which are multi threading which can do multiple tasks at once.
Get Abdoessamadhmayda’s stories in your inbox
Join Medium for free to get updates from this writer.
but javascript is single thread language , it has a single thread called the main thread and it’s responsible for running the javascript code .
So What are Problemes with Synchrounous , Blocking and Single Threaded model of Javascript ?
let’s suppose we want to retrieve some data from the database ,doing some transformation then displaying the data
let res=fetchDataFromDb("endpoint")
let trsformedRes=transformData(res)
displayData(trsformedRes)so what if fetchDataFromDb takes 1 min , we can’t do any trasnformation and we can’t display the data until the 1 min exceeds , if we continue before that time , we will for sure get an error because we will be operating on data which we didn’t yet receive .
so This is a Huge Probleme we need a Way to handle Asynchronous Behavior With Javascript .
Async Javascript — How ?
Javascript is not enaugh to handle asynchronous programming , browsers provide us with functions and api that allow us to register function that should not be executed synchronously and should instead be invoked asynchrnously when a certain event occurs ( passage of time with SetTimeout and SetInterval , user’s interaction with the mouse using addEventListener , or data arrival over network using Promises , Callbacks and Async await)
3-Timeouts and Intervals :
this is the traditional method availaible in javascript for running code asynchronously :
A- SetTimeout :
it’is a function which executes a block of code once after a specified time has elapsed
setTimeout(function,duration,param1,param2,...)the first parameter is a function to run or a reference to a functiond defined elsewhere
the second parameter is a number , presenting the duration in miliseconde to wait before executing the code
after the second parameter you can pass 0 or many parameter as much as the function require .to run
==> To clear Timeouts , you can use the clearTimeout() providing the identifier returning by the timeout as a parameter
let sayHello=function hello(name,age){
console.log(`hello ${name} you have ${age} years old`);
}
const timeOutId=setTimeout(sayHello,3000,"abdessamad",25)
// clear timeOut based on a condition or when unmounting componant to free up the ressources
clearTimeout(timeOutId)- B- setInterval :
it’s a function whicl allow us to run the same code repeatedly at regular interval of time
the signature stays the same as setTimeout
// setInterval exampkes
let seconds=0
function countSeconde(){
seconds+=1
console.log(` it's ${seconds} seconds `)
}
let setIntervalId=setInterval(countSeconde,1000)the setIntervals keep running the same chunk of code over and over again so you should clear the interval when appropriate using the clear interval function
you can achieve the same behavior as setInterval but this time using the setTimeout
NB : timers and intervalls are not part of the javascript itself , they are implemented by the browser and setTimeout and setIntervals are basically names given to this functionality in javascript
let’s continue with callbacks in an other posts : part2 of this subject






