在 javascript 中的另一个线程中运行代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17613396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:58:01  来源:igfitidea点击:

Running code inside another thread in javascript

javascriptmultithreadingsettimeout

提问by uzay95

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.

我想在页面上分离线程以防止 gui 冻结。为此,我正在运行该函数,该函数将使用 setTimeout 在另一个线程中冻结 gui,但仍然冻结。

The code and jsbin link are below:

代码和jsbin链接如下:

<!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üeme" 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>

采纳答案by mishik

Even though you have delegated execution via setTimeoutit 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.

即使您通过setTimeout它委派了执行,它仍将在同一个线程中执行,它只会等待它在队列中的时间,并将推迟任何其他活动,直到它完成。

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

请参考“JS Ninja 的秘密”一书中的这张很棒的图片:

enter image description here

在此处输入图片说明

回答by Arun P Johny

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

javascript(browser) 是一个单线程应用程序,因此即使您在任何时间点使用 setTimeout 也只有一个线程在运行(执行脚本执行、ui 重绘等)。在此处阅读有关计时器如何工作的更多信息

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

由于您每毫秒都有一个脚本运行,它会冻结线程从而阻塞 UI

回答by epoch

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

Javascript 不是多线程的,你可能想看看Web Workers