Skip to main content

Command Palette

Search for a command to run...

Interview question: React performance optimization

Updated
1 min read

I get an interview question, which is: what if there are 10k tasks waiting for process in the front end, how to ensure the tasks does not freeze the page.

My first thought was web worker, we could create web worker and run the tasks on another thread, without blocking the main thread that is responsible for rendering. (Obviously the task is not related to ui rendering, since web worker have no access to the DOM)

While they told me that another solution could be batch processing, like using setTimeout(), and there is one more api could be used in this scenario: requestIdleCallback. This api would register a callback function and would get it executed when the main thread is idle.

Here is a sample:

requestIdleCallback(function(deadline) {
  // check if there is enough idle time in the browser
  while (deadline.timeRemaining() > 0) {
    // execute the task, untill there is no more idle time left
    doSomeTask();
  }
}, {timeout: 2000});  // force execution if the browser is not idle within 2 seconds

The final take away from this interview question is that: to ensure the browser remain smooth and doesn’t freeze, the key is to avoid long-running synchronous tasks that block the main thread.