Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop intense Javascript loop from freezing the browser

I'm using Javascript to parse an XML file with about 3,500 elements. I'm using a jQuery "each" function, but I could use any form of loop.
The problem is that the browser freezes for a few seconds while the loop executes. What's the best way to stop freezing the browser without slowing the code down too much?

$(xmlDoc).find("Object").each(function() {     //Processing here }); 
like image 459
Chris B Avatar asked Apr 03 '09 17:04

Chris B


People also ask

How do I get out of a loop in JavaScript?

The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).

How do I pause a JavaScript loop?

To create pause or delay in a JavaScript for loop, we should use await with a for-of loop. to define the wait function that returns a promise that calls setTimeout with resolve to resolve the promise in ms milliseconds. Then we define the loop function that runs a for-of loop to loop through an array.


1 Answers

I would ditch the "each" function in favour of a for loop since it is faster. I would also add some waits using the "setTimeout" but only every so often and only if needed. You don't want to wait for 5ms each time because then processing 3500 records would take approx 17.5 seconds.

Below is an example using a for loop that processes 100 records (you can tweak that) at 5 ms intervals which gives a 175 ms overhead.

var xmlElements = $(xmlDoc).find('Object'); var length = xmlElements.length; var index = 0; var process = function() {   for (; index < length; index++) {     var toProcess = xmlElements[index];     // Perform xml processing     if (index + 1 < length && index % 100 == 0) {         setTimeout(process, 5);     }   } }; process(); 

I would also benchmark the different parts of the xml processing to see if there is a bottleneck somewhere that may be fixed. You can benchmark in firefox using firebug's profiler and by writing out to the console like this:

// start benchmark var t = new Date(); // some xml processing console.log("Time to process: " + new Date() - t + "ms"); 

Hope this helps.

like image 57
Helgi Avatar answered Oct 01 '22 19:10

Helgi