在javascript中的另一个线程内运行代码 [英] Running code inside another thread in javascript

查看:49
本文介绍了在javascript中的另一个线程内运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

代码和jsbin链接如下:

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>

推荐答案

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

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.

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

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

这篇关于在javascript中的另一个线程内运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆