Running code inside another thread in javascript

后端 未结 4 1317
-上瘾入骨i
-上瘾入骨i 2021-02-07 09:18

I want to seperate thread on the page to prevent freezing of gui. For this, I am running the function which will freeze gui inside another thread with setTimeout but still freez

相关标签:
4条回答
  • 2021-02-07 09:42

    javascript(browser) is a single thread application, so even if you use a setTimeout at any point of time there will be only one thread running(doing script execution, ui repainting etc). Read more about how the timers work here

    Since you have a script running in every millisecond it will freeze up the thread thus blocking the UI

    0 讨论(0)
  • 2021-02-07 09:42

    You can use "Promise" to operate asynchronous function(s):

    Promise document

    A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

    Step 1:

    const dosomethingPromise = (data, otherInput) => {
    return new Promise((resolve, reject) => {
         /* do your work here*/
        resolve(true) /* return result here or you can use reject for execute catch block*/
    })
    

    };

    Step 2: use it like this in your code:

     Promise.resolve(dosomethingPromise(data,otherInput))
            .then((result) => {
                /*your result come here*/
                console.log("Progress finished=>", result);
            }, (error) => {
                console.log(error)
            })
            .catch(console.log);
    

    you can also use Promise and the "all" method instead of "resolve" method to do multiple tasks in a row and get your final result.

    0 讨论(0)
  • 2021-02-07 09:46

    Javascript is not multithreaded, you may want to look at Web Workers

    0 讨论(0)
  • 2021-02-07 09:50

    Even though you have delegated execution via setTimeout it will still be executed in the same single thread, it will just wait for its time in queue and will postpone any other activity until it's done.

    Please refer to this awesome picture from "Secrets of JS Ninja" book:

    enter image description here

    0 讨论(0)
提交回复
热议问题