Optimize Your Code: Don’t Block the Main Thread and Break Up Long Tasks
What is Optimization?
Optimization is the process of making your code faster and more efficient. This is crucial, as a slow website can lead to a poor user experience, causing users to abandon your site. If your pages are loading slowly, tasks are taking too long to return results, or your landing page is sluggish, it’s time to optimize!
What are Tasks?
A task is a piece of work that the browser performs. This includes rendering, parsing HTML and CSS, running JavaScript, and other tasks you may not have direct control over. Of all these tasks, JavaScript is perhaps the largest source of tasks.
What is the Main Thread?
The main thread is a thread where almost all JavaScript code executes and most tasks are run in the browser. It processes tasks one by one in a queue. Tasks taking more than 50 ms are considered long tasks.
Should We Start with Running Long Tasks?
Let’s see how this works. Here’s an example of a long task:
function longTask() {
for (let i = 0; i < 30_000; i++) {
console.log(i);
}
}
This task takes 2.55 seconds, which is considered a long task.
Breaking Up Long Tasks
To optimize, we can break up long tasks into smaller tasks. This is known as yielding. This technique works best with sequential tasks. Here’s an example:
function longTask() {
task('1');
task('2');
task('3');
task('4');
task('5');
task('6');
}
By breaking up the task, we can reduce the total time taken by each task, making it more efficient.
Yielding with setTimeout
Another way to yield is by using setTimeout to defer non-critical tasks. Here’s an example:
function longTask() {
task('1');
task('3');
setTimeout(() => {
task('2');
task('4');
task('5');
task('6');
});
}
Yielding with scheduler.yield()
The scheduler.yield() API is specifically designed for yielding to the main thread in the browser. You can use a scheduler library to achieve this.
Conclusion
To optimize your code, follow these best practices:
- Identify priority tasks that will affect user experience
- Yield to the main thread for critical tasks
- Minimize work per function to 10ms or below to avoid blocking the thread
By following these approaches, you can improve your web performance effectively.
FAQs
Q: What is optimization in coding?
A: Optimization is the process of making your code faster and more efficient.
Q: What is a task in coding?
A: A task is a piece of work that the browser performs, including rendering, parsing HTML and CSS, running JavaScript, and other tasks.
Q: What is the main thread?
A: The main thread is a thread where almost all JavaScript code executes and most tasks are run in the browser. It processes tasks one by one in a queue.
Q: What is yielding in coding?
A: Yielding is the process of breaking up long tasks into smaller tasks to make them more efficient and less resource-intensive.

