Web Workers是Web內容在後臺線程中運行腳本的簡單方法。工做線程能夠在不干擾用戶界面的狀況下執行任務。此外,它們可使用I / O執行XMLHttpRequest(儘管responseXML和channel屬性始終爲null)。建立後,工做人員能夠經過將消息發佈到該代碼指定的事件處理程序(反之亦然),將消息發送到建立它的JavaScript代碼。javascript
//判斷瀏覽器是否支持Worker
if (window.Worker) {
const worker = new Worker('URL');
}
複製代碼
if (window.Worker) {
try {
const worker = new Worker('URL');
worker.onerror = function(msg,fileName,lineno) {
throw msg;
}
} catch (err) {
return err;
}
}
複製代碼
//msg can be an object, an array, or a string
let msg = {};
worker.postMessage(msg);
複製代碼
worker.onmessage = function(e) {
console.log(e.data);
}
複製代碼
// get data from html document
onmessage = function(e) {
console.log(e.data);
}
//catch err
onerror = function(err) {
console.log(err);
}
//some data
postMessage({});
複製代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebWorker</title>
</head>
<body>
<button>開啓計時器</button>
<span class="time"></span>
<script> document.querySelector('button') .addEventListener('click', function handleClick() { console.log('開啓定時器......'); if (window.Worker) { const worker = new Worker('StartTimeLock.js'); worker.postMessage({msg: 'User:你好,我準備開啓定時器了!', state: true}); worker.onmessage = function (e) { console.log(e.data.msg); document.querySelector('.time') .innerHTML = e.data.time; if (e.data.time === 10) { worker.terminate(); } }; } }, false); </script>
</body>
</html>
複製代碼
onmessage = function (e) {
console.log(e.data.msg);
postMessage({msg:'Worker:Worker正在處理您的消息!!'});
if(e.data.state) {
let time = 0;
setInterval(function handleInterval() {
postMessage({time:time++});
},1000);
}
};
複製代碼
我只是個「猥瑣發育的大三銀」,哪裏寫的不對還望大佬們海涵。html