Home > OS >  How to create a non blocking loop JS?
How to create a non blocking loop JS?

Time:04-04

I can not find the solution to this problem:

If you want to test the problem on your side on codepen or others, I leave you a small example:

You need an input type checkbox in html for the test and the JS code:

const array = []
 
for (let i = 0; i < 10000000; i  ) array.push(i)
console.log(array.length)

In fact my problem is that during the execution of this code, if I click on the input, it will only be checked at the end of the execution of the for.

(which is very unpleasant for the customer rendering)

I know it is possible not to block the site while the calculation is done, but then how?

If you have the solution, I'm interested, even a track. Thank you !

CodePudding user response:

One way to do this to use some kind of async pattern to not block the event loop too long. For example create an async iterator like this:

async function doAsyncNTimes(n, process) {
    return new Promise(resolve=>{

        function helper(index) {
            if (index >= n) {
                resolve();
                return;
            }
            process(index);
            setTimeout(()=>{
                helper(index   1);
            }
            )
        }
        let index = 0;
        helper(index);
    });
}

array = [];

doAsyncNTimes(10000, (index)=>{
    array.push(index);
}
).then((ret)=>{
    console.log(array)
});

This way you will only block event loop while one iteration is running, then scheduler the next iteration as soon as possible. You can even make process async if you want, if it can be computationally heavy it can be beneficial. Processing millions of items will take a bit of time, but the UI will not blocked at all.

  • Related