web worker的了解

如,MDN文档中介绍的那样,使用demo如下

<!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>webworker-demo</title>
</head>

<body>
<input id="first" type="text" />
<br />
<input type="text" id="second">
</body>
<script>
var myWorker = new Worker('worker.js');
first.onchange = function () {
// myWorker.terminate();
myWorker.postMessage([first.value, 2]);
console.time();
console.log('Message posted to worker');
}

second.onchange = function () {
// myWorker.terminate();
console.time();
myWorker.postMessage([first.value, second.value]);
console.log('Message posted to worker');
}
myWorker.onmessage = function (e) {
// result.textContent = e.data;
console.log('Message received from worker');
console.log(e.data)
console.timeEnd();
}
</script>
</html>
worker.js,为了模拟计算过程的耗时,使用代码如下:
onmessage = function (e) {
console.log('Message received from main script');
var workerResult = (e.data[0] * e.data[1]);
var now = Date.now();
while (Date.now() - now < 5 * 1000) {
//延迟五秒
}
console.log('Posting message back to main script');
postMessage(workerResult);
}
总结:我们可以把计算过程负责耗时的操作放入worker的线程中。让这个worker线程去计算,这样就计算过程中就不会卡住js线程的异步任务队列正常运行。new Worker(url), 操作时浏览器会去加载这个URL地址指向的js。
 
待续...
posted @ 2018-05-10 11:36  wwr-ready  阅读(194)  评论(0编辑  收藏  举报