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.
Create a variable and set it to the starting value for your counter.
Create a function that:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With