Last active
October 23, 2020 08:54
-
-
Save liuwenzhuang/1e8d4517732d6643f25209a645d54be7 to your computer and use it in GitHub Desktop.
worker and main thread communicate by postMessage and addEventListener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const worker = new Worker('worker.js') | |
// handle data from worker | |
worker.addEventListener('message', (e) => { | |
console.log('worker send data back:', e.data) | |
}, false); | |
// handle error | |
worker.addEventListener('error', (err) => { | |
console.log(`Error: Line ${err.lineno} in ${err.filename} : ${e.message}`); | |
}, false) | |
worker.postMessage('hello'); // send data to worker, large data typically |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function handleData(data) { | |
// handle data and return | |
} | |
self.addEventListener('message', (e) => { | |
// handle data from e.data and send data to main thread | |
const result = handleData(e.data); | |
self.postMessage(result); | |
}, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
stop worker has two ways:
worker.terminate()
in main thread:self.close()
in worker: