利用webworker实现前端的多线程编程


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
head>
<body>
  
  <h1 id="num1">h1>
  <h1 id="num2">h1>
  <button id="start">启动button>

  <script>
    /*
    start.onclick = function(){
      for(let i = 0; i < 999999; i++){
        num1.innerHTML = i
      }
    }
    */
    // 以上做法在for循环过长的情况下会阻塞主线程,故应使用webworker方式另外新建一个进程处理
    start.onclick = function(){
      
        var w = new Worker('worker.js')
        w.onmessage = function(e){
      
          num1.innerHTML = e.data
        }
        w.postMessage('')
    }

  script>
body>
html>
// 另外新建的线程worker.js
onmessage = function (e){
     
  for(let i = 0; i < 999999; i++){
     
    this.postMessage(i)
  }
}

你可能感兴趣的:(前端,JavaScript,javascript,js,前端)