进程与线程

进程:Process
线程:Thread
摘自Stackoverflow

Both processes and threads are independent sequences of execution.
The typical difference is that threads (of the same process) run in a shared memory space,
while processes run in separate memory spaces.
进程和线程都是独立的执行序列。
典型的区别在于(相同进程的)线程运行在一个共享内存空间,进程运行在单独的内存空间。

Html5 Web Workers API 与thread 线程的概念相关联

A worker is an object created using a constructor (e.g. Worker()) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. Thus, using the window shortcut to get the current global scope (instead of self) within a Worker will return an error.

worker是使用运行命名的JavaScript文件的构造函数(例如Worker())创建的对象 - 此文件包含将在工作线程中运行的代码; wokers在与当前窗口不同的另一全局上下文中运行。 因此,使用窗口快捷方式在Worker中获取当前全局范围(而不是self)将返回错误。

直接通过实践理解这句话:
创建 file.js

   var i = 0;
   function counter() {
    i = i + 1;
    postMessage(i);
    setTimeout(counter, 500);
}
   counter();

html不分代码

     <button onclick="start()">Start</button>
     <button onclick="end()">End</button>
     <div id="result"></div>

主页的js部分代码

   var worker,
       result = document.getElementById('result');
   function start() {
       if(typeof (Worker) === "undefined") {   //判断你浏览器是否支持 Worker

           worker = new Worker("file.js"); 
           worker.onmessage = function(event) {
                  result.innerHTML = event.data  // 传递过来的i值 被储存在event.data中
             }
      } else {

           result.innnerHTML = "你的浏览器不支持 Web Worker";
     }

   }

   function end() {
      worker.terminate();
 }

主要用到了 Web Worker 全局下的 postMessage( ) 向HTML中传递数据。

通常用到Web Worker的地方是需要消耗CPU很多时间的任务, 这样可以不阻塞主线程继续执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值