-
-
Save jsteenkamp/8f68cf4c60291ba12ea94eff1835868c to your computer and use it in GitHub Desktop.
Long polling with web workers
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 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