How to artificially control the time that JS code snippets take up the (Main Thread) of the main process?

our Web application is relatively large and does a lot of computing in the background (or in the front-end JS running environment). This leads to obvious stutters in the user"s operations, such as touch and move, etc. The reason is that Main Thread is occupied by the code that does js in the background.

I looked up a lot of information and saw that Google"s Web development advice says to limit the length of each JS task to 50ms and to allow as much free time as possible for Main thread so that Main Thread can handle user input operations.

excuse me, how can I control how long a method will run?
is to write a large function into multiple small function? Or change the for loop or something to how often it is executed?

are there any related articles and tutorials to learn?

Thank you

Mar.30,2021

function f200() {
    for (let i = 0; i < 200; iPP) {
        //doSomething
    }
    
}


function f100() {
    return new Promise((reslove) => {
        setTimeout(() => {//Promisemicrotask promise  setTimeout
            for (let i = 0; i < 100; iPP) {
                //doSomething
            }
            reslove('f100');
        }, 0)
    })
}



Promise.all([f100(), f100()]).then(([r1, r2]) => {
    console.log(r1, r2)
})

for example, a does a lot of computation f200 and splits it into two f100 . The point is that you can't execute a lot of Synchronize code at once.


Let me make up what I think is the most beautiful way:


es6es5setTimeoutsetInterval:

function do() {
  setTimeout(function () {
    /**/
    do();
  },0)
}
do();
The advantage of this is that every time do executes, it becomes an asynchronous task, which is inserted into the task queue, and it is not so easy to block the process.

Menu