mdn web worker
1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./app.js" defer></script>
</head>
<body>
<button id="btn"> 눌러보세요</button>
<div id="result"></div>
</body>
</html>
document.querySelector('#btn').addEventListener('click', function () {
var worker = new Worker('./worker.js');
worker.addEventListener('message', function(e) {
var div = document.createElement('div');
div.textContent = e.data;
console.log(e.data)
document.querySelector('#result').appendChild(div);
worker.terminate();
});
worker.postMessage('work');
});
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
self.addEventListener('message', function(e) {
console.log(e.data); // 일해라 워커!
if(e.data === "work"){
sleep(3000); // 3초가 걸림을 표현
self.postMessage("send my message");
}
});