Explain Codes LogoExplain Codes Logo

Violation Long running JavaScript task took xx ms

javascript
performance
optimization
async-programming
Nikita BarsukovbyNikita Barsukov·Jan 26, 2025
TLDR

To tackle long task warnings, apply asynchronous methods that split exhaustive calculations into manageable chunks. Use setTimeout or requestAnimationFrame for non-blocking loops or utilize the power of async/await within Promises to frequently yield control to the event loop.

Here's a neat example:

function processAsync(array, process, done) { // Start the loop at zero (all good things start at zero) (function loop(i) { // If we're not done with the array, if (i < array.length) { // Take a breath (set timeout as 0) setTimeout(() => { // Process the nth item like a champ process(array[i]); // Move on to the next one loop(i + 1); }, 0); } else { // Drop the mic when we're done done(); } })(0); } processAsync(largeArray, item => { // Item, prepare to be processed }, () => { console.log('Processing complete. Time for a tea break'); // British devs love tea });

This code progressively processes largeArray, ensuring the browser stays alert during extensive operations. Adjust your process accordingly to bring out peak performance.

Figuring out performance bottlenecks

Understanding the origin of performance bottlenecks can be integral to improving long running JavaScript tasks. Chrome's profiler in its Performance tab is a handy tool which can identify such tasks and potentially reveal inefficiencies and unexpected behaviour, helping you to patch things up.

Warnings and refactoring: Cleaning up the mess

Look at console warnings within Chrome as signposts pointing towards your performance problems. Source control history can provide an instant replay of when an offending alteration was made. A binary approach - trimming code sections one by one - can assist in identifying the culprit causing your program to drag its feet.

Smoothing out the DOM: Keep it lean, keep it clean

Performance issues often stem from the DOM Mayhem. Trim down excessive DOM depth, optimize node management, and streamline your event listeners. Don't forget to compress and optimize CSS to prevent an extensive reflow, otherwise your performance could take a nosedive.

Asynchronous for the win: Don’t let them wait

Turn synchronous tasks to asynchronous operations. Use setTimeout or Promise.resolve to magically convert your tasks into non-blocking affairs. Or use Web Workers for a parallel processing detour which won't disturb the tranquility of the main thread.

Profile for the lead role: Be the star of your own JavaScript show

Step up from console logs

While console warnings are the gatekeepers of performance issues, Chrome's profiler is the secret passage leading to the performance treasure vault. Devote time to performance testing and use the visualization tools to dissect long tasks.

Benchmarking for pros: Up your game

Incorporate benchmarking libraries like Benchmark.js into your debugging arsenal for performance insights that will make you go "Whoa". These libraries spill the beans on your function runtimes, pointing out the gremlins in your code.

Refinement is key: From clunky to sleek

Once the bugs come to light, roll up your sleeves and get down to refining your code. This means optimizing algorithmic complexity, leveraging Web Workers if feasible, and using well-timed tools like lodash for debouncing or throttling event handlers.

Cross-browser compatibility: Spread the love

Test, test, and test your application across various browsers. Some demons may be exclusive to Chrome, and understanding your app's performance on other browsers is key to delivering a smooth, all-inclusive browser experience.