uzay95
uzay95

Reputation: 16622

Running code inside another thread in javascript

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 freezing.

The code and jsbin link are below:

<!DOCTYPE html>
<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"
  type="text/javascript"></script>
  <meta charset="utf-8" />
</head>
<body>
  <div id="div1"></div>
  <div id="div2"></div>
  <input type="button" value="düðme" id="btn" />

  <script type="text/javascript">
      $("#btn").on("click",function(){
        $("#div1").html(new Date());
      });

      $(document).ready(function(){
        setTimeout(function() { count(); },1);
      });

      function count(){
        for(var i =0;i<100000;i++){
          $("#div2").html(i);
        }
          $("#div2").append(new Date());
      }
  </script>

</body>
</html>

Upvotes: 18

Views: 28514

Answers (5)

Hagay Levy
Hagay Levy

Reputation: 101

Try to use web worker in order to run long tasks in parallel. You can read all about it https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

Upvotes: 0

Ali Khajehpour
Ali Khajehpour

Reputation: 134

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.

Upvotes: 2

mishik
mishik

Reputation: 10003

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

Upvotes: 15

epoch
epoch

Reputation: 16605

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

Upvotes: 10

Arun P Johny
Arun P Johny

Reputation: 388326

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

Upvotes: 6

Related Questions