Tag Archives: nonblocking

Blocking and Non-blocking Code

A Tale of Two Burger Joints

Restaurant #1

You wait in line so the cashier can take your order. There’s about 4 guests ahead of you, and an ever increasing line of people behind you. Once you place your order, they give you a pager that lights up and vibrates when your food is ready. You step off the line and wait with the other people who placed their order before you. Eventually your buzzer goes off, you take your tray of deliciousness from the counter, and squeeze past the lines of people waiting to find a table. This whole process takes about 20-30 minutes.

Restaurant #2

There are about 3 people in ahead of you in line. The cashier takes the order of the person in front. Then, after about 15 minutes, the customer’s food is ready and they take it and leave. Now there are only 2 people in front of you in line, and the same process happens: no other orders can be taken until the transaction is complete. You have to wait until everyone in front of you places their order, pays, and gets their food. The whole process takes a really long time.

So What?

You may be thinking that Restaurant #1 sounds like any fast food place, and that you would never see a place like Restaurant #2 in business.

What does this have to do with code? Code can be blocking, like Restaurant #2. Code can also be non-blocking, like Restaurant #1. Javascript by nature is non-blocking and allows asynchronous functions to exist. From what I’ve gathered, it can take a little getting used to if you are used to writing blocking code that has to go in a certain sequence.

Some actions that need to take place in a program are asynchronous by nature.  For example, say you need to retrieve data from a database – it takes time for your program to go to the database, get the data, and return it to the client side of your app.  Meanwhile, the rest of the page still needs to load.  It would not make for a good user experience for them to look at a blank screen while the database was accessed.  Usually, you might see most of the page loaded, and maybe a spinner or message that lets the user know they are waiting for the data.  When writing code in Javascript, it’s important to keep asynchronous operations in mind so that your application functions the way you want it to.