<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</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中,当for循环处理大量数据时如何阻塞主线程,并提出通过引入Web Worker来创建额外的进程,从而实现计算密集型任务的异步处理,保持用户界面的流畅响应。
181

被折叠的 条评论
为什么被折叠?



