DEV Community

Shubham Bendkhale
Shubham Bendkhale

Posted on

Understanding Blocking and Non-Blocking Code: An Easy Guide for Developers

Blocking:
Blocking code means that the execution of code stops at a particular point until the operation is completed. During this time, no other code can be executed. It's like standing in line at the bank until your turn is over.

Imagine you're at a busy restaurant with only one chef. You order a dish, and the chef starts cooking it. No other orders can be cooked until your dish is finished. That's like blocking code: everything stops until the current task is done.

Non-Blocking:
Non-blocking code allows other operations to be executed while waiting for the completion of the current operation. Think of it as placing your order at a drive-through and then moving forward to pick it up while someone else places their order.

Now, imagine the restaurant has multiple chefs. You place your order, and while one chef starts cooking your dish, other chefs can cook other orders at the same time. This means that everyone gets their food faster. That's like non-blocking code: multiple tasks can be handled simultaneously, making things more efficient.

Example:

Blocking:

const fs = require('fs');

let data = fs.readFileSync('file.txt'); 
console.log(data);

Enter fullscreen mode Exit fullscreen mode

Non-Blocking:

const fs = require('fs');

fs.readFile('file.txt', (err, data) => {
    if (err) throw err;
    console.log(data); 
});

console.log('This runs immediately, even before the file is read');
Enter fullscreen mode Exit fullscreen mode

In the non-blocking example, fs.readFile doesn't stop the execution of the code. Instead, it runs the callback function once the file has been read, allowing other code to run in the meantime.

Why It Matters:
Blocking Code can make your application sluggish, as it waits for each operation to complete before moving on.

Non-Blocking Code helps in building responsive, efficient applications by handling multiple tasks simultaneously.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay