Skip to content

Instantly share code, notes, and snippets.

@vitkon
Created June 7, 2017 22:58
Show Gist options
  • Save vitkon/91f990c0296fd1d527c5e7f6e51ce5ea to your computer and use it in GitHub Desktop.
Save vitkon/91f990c0296fd1d527c5e7f6e51ce5ea 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