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 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>
3
  • 3
    That will still be executed in the same thread. Everything will be executed in the same thread. The only exception is WebWorkers. Commented Jul 12, 2013 at 11:00
  • but jquery ajax requests are working in different thread if we say async: true. I'm now searching to find good info about webworkers. I need to run something in other threads while gui still touchable and loading another data from network. Commented Jul 12, 2013 at 11:04
  • 2
    The callback for that ajax request will still be executed in the same thread. async:true will just mean that browser can spend some time dealing with other tasks while it waits for ajax call results. Commented Jul 12, 2013 at 11:05

5 Answers 5

15

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

Sign up to request clarification or add additional context in comments.

1 Comment

So what about the Async/Await methods ? what they are used for ? I was sure that asynchronous job , should run on separate thread from the thread which execute it, for example in desktop/android application we can make none blocking UI task in the background and update the UI when the async job is done. so what this methods are used for in Javascript/Typescript and why they are called Async ? basarat.gitbooks.io/typescript/docs/async-await.html
11

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

Comments

6

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

Comments

3

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.

Comments

0

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

1 Comment

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.