• js中的webworker


    js中的webworker

    webworker的作用类似于java的多线程

    以独立文件的形式运行webworker

    1. index.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <title>Document</title>
      </head>
      <body>
          <div id="showBox"></div>
          <script>
              if(window.Worker) {
                  var worker = new Worker("./test.js");
                  worker.postMessage(10);
      
                  worker.onmessage = function(event) {
                      document.getElementById("showBox").innerText = event.data;
                      if(event.data == 10) {
                          worker.terminate(); // 终止worker
                      }
                  }
              }else{
                  alert("你的浏览器不支持worker");
              }
          </script>
      </body>
      </html>
      
    2. test.js

      var i = 0, count = 0; 
      
      self.onmessage = function(e) {
          count = e.data;
      }
      
      function countNumber() {
          if(i < count){
              i = i + 1;
              self.postMessage(i); // 将信息发送到主线程上
          }
          console.log(i);
          setTimeout(countNumber, 500)
      }
      countNumber();
      
  • 相关阅读:
    费用流入门
    网络最大流入门
    假期编程
    假期编程
    假期编程
    假期编程
    假期编程
    假期编程
    假期编程
    假期编程
  • 原文地址:https://www.cnblogs.com/ye-hcj/p/10352897.html
Copyright © 2020-2023  润新知