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(); });