Running code inside another thread in javascript

[亡魂溺海] 提交于 2020-12-01 02:34:11

问题


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>

回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/17613396/running-code-inside-another-thread-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!