2023. 11. 17. 11:27ㆍ[프론트엔드]_/[Javascript]_ES6
개요
자바스크립트 코딩을 하다보면 복잡한 계산식의 경우 쓰레드 처리를 하고 싶을 때가 있을 수 있습니다.
JS 에서 Web Worker 로 쓰레드 구현이 가능합니다.
오늘은 Web Worker 의 간단 구현을 해보도록 하겠습니다.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
Using Web Workers - Web APIs | MDN
Web Workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. In addition, they can make network requests using the fetch() or XMLHttpRequest APIs. Once
developer.mozilla.org
틀린것이 있을 수 있으니 양해부탁드립니다.
틀린점은 댓글로 알려주시면 정말 감사드리겠습니다.
학습
1. 생성자
const testWorker = new Worker("/resources/web/js/worker.js");
메인 쓰레드에서 웹워커를 생성합니다.
그럼 페이지에서 백그라운드 쓰레드를 생성하게 되고 해당 worker.js 파일을 읽습니다.
2. worker.js
onmessage = function (e) {
console.log('Worker: receive main script');
const result = parseInt(e.data) + 1;
if(isNaN(result)){
postMessage('Please insert number plz');
} else {
const workerResult = 'Result' + result;
console.log('Worker : Postion message back to main script');
postMessage(workerResult);
}
}
worker.js 에서는 메인 쓰래드가 postMessage로 요청한 메시지를 수신받기 위한 이벤틀 리스너를 구현합니다.
결과 혹은 메세지는 메인쓰레드가 postMessage 를 사용한 것처럼 같은 방식으로 전달합니다.
3. 메인쓰레드에서의 요청
function workerTest() {
// 워커 테스트 버튼 클릭 이벤트
console.log("worker Test Here");
let inputValue = parseInt($("#worker_test_input").val());
console.log(inputValue);
if(window.Worker){
testWorker.postMessage(inputValue);
console.log('Message posted to worker');
testWorker.onmessage = function(e){
console.log(e.data);
console.log('Message received from worker');
}
} else {
console.log('Error');
}
}
생성자 객체에 postMessage 함수를 사용해서 data 를전달하고
이를 생성자 객체의 onmessage 함수를 사용해서 데이터를 읽어드립니다.
결과
다음 Worker 공부시 심화버전을 다루도록 하겠습니다.
감사합니다.
'[프론트엔드]_ > [Javascript]_ES6' 카테고리의 다른 글
[ES6]_Proxy get()에서의 Depth에 따른 prop 의 변화 (0) | 2023.10.26 |
---|---|
[ES6]_Proxy 란 ? (0) | 2023.10.25 |
[ES6]_Execution Contexts (실행 컨텍스트) 이해 (0) | 2023.06.19 |
[ES6]_var 와 let,const 의 차이 (1) | 2023.06.19 |
[Element Event 탐지]_F12 개발자 도구 활용법 (0) | 2022.09.01 |