Knowing the meaning of terms and what they actually do and represent could greatly improve your comprehension ability while writing code or following lessons and tutorial classes. In this article I'll walk you through understanding the synchronous and asynchronous way of writing JavaScript code.
JavaScript is single threaded. This means that instructions in javascript are only executed one at a time and in order. Here's a quick example:
console.log(" Hello! ");
console.log(" I'm ");
console.log(" Daniel ");
RESULTS
// >> Hello!
// >> I'm
// >> Daniel
In the above example we see that the three console.log
statements were executed in sequence. This would further tell us that JavaScript in default, is synchronous because it executes one statement at a time and does not allow for parallel execution of statements.
Synchronous
In programming, we can explain synchronous code as a group of statements that executes in sequence. This implies each statement in your code is executed one after the other, so each statement has to wait for the previous one to finish executing.
Like what we had in the above code block, we could easily conclude that the statement was one with a synchronous nature.
Selecting the time you need something to behave synchronously or not is what really matters. There are some downsides to writing synchronous code. Because statements are excuted one at a time, this means that without the completion of that particular command; nothing else can be done. So synchronous code is
-
Blocking
in nature: This means that it blocks every other action until the first action is completed. - Makes for a Bad user experience: Say you're creating a new post as a user, or calling an API give us new timeline updates. Doing this synchronously would mean that the user would have to wait until that particular action is complete to perform something else on the page. So whatever and however long it takes an action to complete, every other action on the page is suspended until the first/above action is complete.
So we definitely need to have a way to write our JavaScript code where we could be performing a task in the background while allowing the other tasks to keep on running.
Asynchronous JavaScript
I'll try to show you in a simple manner an example on how asynchronous code could be written on the frontend with setTimeout()
.
setTimeout() is only available on the frontend because it is provided by the web API and as such, it cannot be used while writing server-side code.
The setTimeout()
method takes in two parameters: a function which you're about to evaluate, and the time ( in milliseconds ) you want it to delay before displaying the result. Here's a quick example.
setTimeout(
() => {
console.log(" Hello I am Daniel ")
}, 5000)
// Results
// ......... (wait for five seconds first)
>> Hello I am Daniel
So as we have seen, using the setTimeout()
method, we could delay code execution and remove the code execution from the normal flow of execution. Because the we have removed the peice of code from the normal flow of exection, the commands below can now be executed while our asynchronous peice of code waits.
Let us look at an example where we put synchronous and asynchronous code side by side:
// first statement
console.log(" Hello");
// second statement
setTimeout(
() => {
console.log(" This tutorial is getting a little bit long ")
}, 5000);
// third statement
console.log(" World ");
// RESULTS
>> Hello
>> World
// ....... After five seconds...
>> This tutorial is getting a little bit long
You'll notice that the third statement was called before our asynchronous block of code ( second statement ) and, our setTimeout()
asynchronous code is delayed for 5 seconds ( 5000 miliseconds ) before it is called and executed.
But what if we reduce the time to zero? what would be the result?
console.log(" Hello");
setTimeout(
() => {
console.log(" This tutorial is getting a little bit long ")
}, 0);
console.log(" World ");
// RESULTS
>> Hello
>> World
// ... Immediately after the third execution...
>> This tutorial is getting a little bit long
We still see that the asynchronous code block was still executed last.
I will try to explain this as clear as I can.
Since setTimeout()
is a browser API, its working mechanism is controlled by the browser API and not JavaScript itself. Here's what happens when you put use the setTimeout()
method:
- Once the
setTimeout()
is called, the block of code goes out of the normal execution stack, and goes to the web API where the timer is checked until the timer you set on it ellapses. - Now that the asynchronous code has gone out of the normal execution stack, space has been freed up to execute other executables on the stack.
- After the time given has ellapsed, the web API cannot just push back the result into the stack, else you'll just have things appearing in the middle of an ongoing execution.
- The Web API push the callback which is returned after the ellapsed time unto the task queue.
- Next, The Event Loop : the event loop has one simple responsibility, it checks the stack to see if it's empty, once it is empty, it looks at the task queue and takes the first thing on the queue and pushes it unto the stack which runs it.
So now we see why the setTimeout()
method is displayed last even if 0
is passed into it as the timer.
Recap
- JavaScript is single threaded.
- Synchronous JavaScript code executes one after the other, and each statement waits until the previous one is first completed
- Asynchronous code provides a way we could write non blocking code that returns a callback to us once it completes.
- `setTimeout() is a method provided by the browser API that helps us write asynchronous code on the client side.
setTimeout()
takes two parameters: The function to be executed, and the execution delay time.
While there are some other ways of writing Asynchronous code, even for the serverside, we didn't cover it in this article. Here are some interesting contents you could go ahead to look into:
Find me on twitter @spillcode and tell me if this helps you! Thanks!