Optimize long task in JavaScript

Optimize long task in JavaScript

As you know, JavaScript is single-threaded, meaning it can only execute one task at a time. If a task takes too long to complete, it can cause the browser to become unresponsive or laggy.

This example here is a long task, which makes browser laggy and user can not do anything else.

Long task funtion

Run Performance tab, you can identify the long task that are blocking the main thread and causing the browser to become laggy.

Performance tab

When understanding Event Loop from my previous post (https://www.dhirubhai.net/posts/pdthien_wecommit100xshare-eventloop-javascript-activity-7219225120928673793-Gk6y/), you can optimize this by combining setTimeout and splitting it into small tasks. These tasks are then placed in MacroTask Queue.

In this example, we split long task into 10 small tasks. After doing this, browser remains smooth.

Break long tasks

Open Performance tab, you can now observe multiple smaller tasks instead of a single long task.

Performance tab

This matters because when tasks are broken up, the browser can respond to higher-priority work much sooner, such as user interactions or rendering like the below picture (zoom in the picture above). That's why the browser remains smooth.

User interactions task



Kh?i Nguy?n Tr?ng

?Performance Tuning | Backend developer | AWS | GCP | Japanese(N2)

7 个月

Thanks for sharing

Nguyen Trung Nam

Senior Software Architect @ VPS Securities JSC

8 个月

C?m ?n bài chia s? c?a em nhé, vi?c chia nh? task ok ??y, anh s? th? lu?n cách c?a em trong các bài toán t?i ?u s?p t?i c?a anh. Hi?n t?i các long task anh x? lí ?a lu?ng dùng web worker.

thanks, it's very helpful ??

Ben Dennison

Helping Scale-Ups Build Their Engineering Teams - Tech for Good Consultant at SR2 | Socially Responsible Recruitment | Certified B Corporation? | ?? [email protected] | ??+442037577334

8 个月

Thanks for sharing!

Tuan Nguyen Anh

Full-stack Software Engineer

8 个月

Interesting! How about utilizing the Web Worker API. It creates a dedicated thread to run heavy tasks without interfering to the user interface. https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers Hope to have your detailed information about this topic soon!

回复

要查看或添加评论,请登录

Ph?m ?ình Thi?n的更多文章