web worker的瞭解

如,MDN文檔中介紹的那樣,使用demo以下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>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。
 
待續...
相關文章
相關標籤/搜索