webworker

Geonil Jang·2021년 1월 11일
0
post-thumbnail
post-custom-banner

webwork 사용해보기

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>
  1. app.js
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');
  });
  1. worker.js
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");
    }
   
});

profile
takeaways
post-custom-banner

0개의 댓글