Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 786
uzay95 Avatar asked Jul 12 '13 10:07

uzay95


People also ask

Does SetTimeout run on different thread?

Bookmark this question. Show activity on this post. Sure enough, clicking the button causes the browser to hang. This tells me that setTimeout() does not run on a separate thread.

What is thread of execution JavaScript?

Thread in computer science is the execution of running multiple tasks or programs at the same time. Each unit capable of executing code is called a thread.

Is JavaScript single threaded or multi thread?

JavaScript is a single-threaded language because while running code on a single thread, it can be really easy to implement as we don't have to deal with the complicated scenarios that arise in the multi-threaded environment like deadlock. Since, JavaScript is a single-threaded language, it is synchronous in nature.


1 Answers

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

like image 121
mishik Avatar answered Oct 15 '22 04:10

mishik