如,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>
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);}