Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a loop in Javascript that doesn't block the UI? [duplicate]

Tags:

javascript

I have some javascript on my page that takes a very long time to execute (between 10-30 seconds)

The code basically look like that :

//Iterate over all the elements in the array
for(int i=0; i<array.length; i++){
   //Complex stuff for each element
}

The problem is that while this code is executing, the UI is not responsive.

Is there any way to solve this issue? I know javascript has some sort of asynchrony but I never really used it before...

Also, the order the elements are processed must always be the order that they appear in the array.

EDIT : I tried the solution below with setTimeout() and in the "duplicate", but it still doesn't fix my problem. I guess it's because the size of my array is not very big BUT the calculation for each element is pretty big.

Also the UI I want to be responsive is an animated loading gif. Since the calculation for each item is too big, the animation is sloppy.

like image 289
Gudradain Avatar asked Feb 12 '23 18:02

Gudradain


1 Answers

Create a variable and set it to the starting value for your counter.

Create a function that:

  1. Does whatever the body of the loop does
  2. Increments the counter
  3. Tests to see if the counter is still under the length and, if it is, calls the function again

At this point you will have functionality equivalent to what you have already.

To pause between each call of the function, and allow time for other functions to fire, replace the direct call to the function with a call to setTimeout and use the function as the first argument.

var counter = 0;
function iterator () {
    //Complex stuff for each element
    counter++;
    if (counter < array.length) {
        setTimeout(iterator, 5);
    } 
}
like image 112
Quentin Avatar answered Feb 15 '23 08:02

Quentin