Unresponsive UI and a busy main thread?

amythical

amythical

Posted on May 19, 2024

Unresponsive UI and a busy main thread?

Situation
Say you are in a situation where you have a Popup with a close button and a loader asking you users to wait while you process a lot of data before you display it to them.
You have to carry out computation on a list of items before displaying them.
UX Problem
If we carry this processing out in the main thread, if the users click the close button - it may not respond as the main thread is busy and not listening for the close button event.

WebWorkers may not work if dom elements
My first goto would be Web Workers but sometimes we cannot use a worker because we may need to use DOM Elements with the values in the list.

Solution
So we need to yield control from time to time to process other events in the main thread.
But there is no native sleep method so I am using the following custom function, 'fakeSleep'

  fakeSleep(pTimeSec) {

    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve();
      }, pTimeMillisec);// 16 ms is a good value (60 fps/1 sec ~ 16 ms per frame)
    });
  }

  processingFunction1();
   fakeSleep(0.1);// or 0.05 anything you wish 
  processingFunction2();
   fakeSleep(0.1);// or 0.05 anything you wish 
  processingFunction3();
   fakeSleep(0.1);// or 0.05 anything you wish 
  processingFunction4();
Enter fullscreen mode Exit fullscreen mode

By yielding control even for a small amount of time in between our heavy processing, we can make the UI responsive.

This is a solution for extreme situations but I have had the need to use this while processing a lot of data on the client.

Cheers.
Happy to hear how you handle such situations.

💖 💪 🙅 🚩
amythical
amythical

Posted on May 19, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related