Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.