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.
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.linkedin.com/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)
1yThanks for sharing
Senior Software Architect @ VPS Securities JSC
1yCả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.
--
1ythanks, it's very helpful 😁
Helping Scale-Ups Build Their Engineering Teams - Tech for Good Consultant at SR2 | Socially Responsible Recruitment | Certified B Corporation™ | 📧 Ben@sr2rec.co.uk | 📞+442037577334
1yThanks for sharing!
Full-stack Software Engineer
1yInteresting! 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!