A short guide to Blocking Code in Javascript

A short guide to Blocking Code in Javascript

·

2 min read

When an app runs in a browser/server and it executes and an intensive chunk of code without returning control, the APP can appear to be frozen.

This is called blocking. The app is blocked from continuing to handle user input and perform other tasks until the app returns control of the processor.

Blocking Code in Browser

const btn = document.querySelector('button'); 
btn.addEventListener('click', () => {
    let myDate; 
    for(let i = 0; i < 10000000; i++) {
        let date = new Date(); 
        myDate = date; 
    }
    let pElem = document.createElement('p');
    pElem.textContent = 'Paragraph Added..!!!'; 
    document.body.appendChild(pElem); 
});

When running this and clicking the button, the paragraph does not appear until after the date has finished being calculated (10 million times).

Blocking code in Server

const fs = require('fs'); 
console.log("Start reading"); 

// blocks here until file is read
cost data = fs.readFileSync('/file.md'); 
console.log("Finished reading"); 
moreWork();

The function moreWork() is executed only after the file-read is finished. Until then, the control is not returned and thus no other code-block is executed.

Prefer asynchronous coding to overcome the blocking and to improve the performance of the application.


Removal.AI - [SPONSOR]

Remove background from multiple images in a single upload straight to your desktop using Bulk Photo Background Remover for Windows.

  • ✅ Drag & Drop Multiple Images
  • ✅ Optimize Product Images
  • ✅ Select Your Background
  • ✅ Set Your Output Size
  • ✅ Exceptional Results

Removal AI

Visit -> Removal AI

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!