I want to process a large array without blocking the UI, but I also need the processed array to reprint some features in a map. I have used the first approach in the most voted answer of this question: Best way to iterate over an array without blocking the UI
The problem is that when the function finish the first chunk and therefore make use of setTimeout, the thread is released and the map only repaint the first chunk_size elements, in this case 100 but I want all 1000 elements to be multiplied by 10.
I tried to use promises but I am missing something because the same problem occurs. In this JSbin you can check what happens: https://jsbin.com/fatijosufu/edit?js,console An array of 1000 elements is created and the processLargeArray function should multiply each element by 10. When the array is printed after calling the function, only the 100 first elements have been processed, this is, only the first chunk of the array.
const array1 = []
for (let i = 0; i < 1000; i++){
array1[i] = i;
}
function processLargeArray(array) {
// set this to whatever number of items you can process at once
var chunk = 100;
var index = 0;
function doChunk() {
var cnt = chunk;
while (cnt-- && index < array.length) {
array[index] = array[index] * 10;
++index;
}
if (index < array.length) {
// set Timeout for async iteration
setTimeout(doChunk, 1);
}
}
doChunk();
}
processLargeArray(array1);
console.log(array1);
The way I tried to solve the problem with promises, but that is not working: https://jsbin.com/fatijosufu/edit?js,console
const array1 = []
for (let i = 0; i < 1000; i++){
array1[i] = i;
}
function processLargeArray(array) {
return new Promise((resolve, reject) => {
// set this to whatever number of items you can process at once
var chunk = 100;
var index = 0;
function doChunk() {
var cnt = chunk;
while (cnt-- && index < array.length) {
array[index] = array[index] * 10;
++index;
}
if (index < array.length) {
// set Timeout for async iteration
setTimeout(doChunk, 1);
}
}
doChunk();
resolve(array);
});
}
processLargeArray(array1).then((array) => {
console.log(array);
});