Maximizing JavaScript Performance with Concurrency: Tips and Tricks for Web Developers
Mastering the Basics of Concurrency in JavaScript
The first question is, what exactly is concurrency? In simple terms, concurrency is the ability of a programming language to execute multiple tasks simultaneously. To put it into perspective, let’s take a look at an example.
Why Concurrency is Even Required?
You all have written code like this:
fetch(...).then(function handleResponse(res) {
// Do something with the response.
})
Have you ever noticed that while sending an AJAX request, it takes a long time, but your application doesn’t stop and wait for the request to come back? Have you ever wondered how this happens?
We can’t stop the whole application and wait for our tasks to complete before the user can start working. We need to move some tasks to the background so they can be done without disturbing our main thread.
One thing at a time
JavaScript is a single-threaded language, which means that it can only do one thing at a time. It cannot launch multiple threads like other languages, (poor JavaScript). So, how does it handle multiple tasks simultaneously? Well, here is an image to illustrate: