Skip to content

Instantly share code, notes, and snippets.

@jsteenkamp
Forked from vitkon/webWorker.js
Created October 25, 2020 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsteenkamp/8f68cf4c60291ba12ea94eff1835868c to your computer and use it in GitHub Desktop.
Save jsteenkamp/8f68cf4c60291ba12ea94eff1835868c to your computer and use it in GitHub Desktop.
Long polling with web workers
function workerFunction() {
this.addEventListener('message', (e) => {
console.log('log2: ', e);
fetchUrl(e.data);
})
const fetchUrl = (url) => {
fetch(url)
.then((response) => {
console.log(response);
return response.json();
})
.then((jsonObj) => {
this.postMessage(jsonObj);
setTimeout(() => fetchUrl(url), 500);
})
.catch((err) => {
console.error(err);
});
}
}
var dataObj = '(' + workerFunction + ')();';
var blob = new Blob([dataObj]);
var blobURL = URL.createObjectURL(blob, {
type: 'application/javascript; charset=utf-8'
});
window.worker = new Worker(blobURL);
worker.postMessage('https://httpbin.org/ip');
worker.onmessage = function(e) {
console.info('new stuff:', e.data);
}
const button = document.getElementById('stop')
button.addEventListener('click', () => {
worker.terminate();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment