Optimize long task in JavaScript
Ph?m ?ình Thi?n
??Lead Software Engineer @ MISA JSC | Youtube “Ph?m ?ình Thi?n - T?i ?u Frontend”
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.
Run Performance tab, you can identify the long task that are blocking the main thread and causing the browser to become laggy.
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.
Open Performance tab, you can now observe multiple smaller tasks instead of a single long task.
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.
?Performance Tuning | Backend developer | AWS | GCP | Japanese(N2)
7 个月Thanks for sharing
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.
--
8 个月thanks, it's very helpful ??
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!
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!