Created
November 9, 2022 19:05
-
-
Save Kuzmenko-Pavel/eefdb66969d8473cf669b5711a4182c7 to your computer and use it in GitHub Desktop.
web worker check connection
This file contains hidden or 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
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <title>Web Workers</title> | |
| </head> | |
| <body> | |
| <script> | |
| if (window.Worker) { | |
| const myWorker = new Worker("worker.js"); | |
| myWorker.postMessage("https://auction-dev.prozorro.sale/") | |
| myWorker.onmessage = function(e) { | |
| console.log(e.data); | |
| } | |
| } else { | |
| console.log('Your browser doesn\'t support web workers.'); | |
| } | |
| </script> | |
| </body> | |
| </html> |
This file contains hidden or 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
| const fetchWithTimeout = function (resource, options = {}) { | |
| const {timeout = 1000} = options; | |
| const controller = new AbortController(); | |
| setTimeout(() => controller.abort(), timeout); | |
| fetch(resource, { | |
| ...options, | |
| signal: controller.signal | |
| }).then( | |
| response => response.ok ? postMessage('Connection OK') : postMessage('Connection Lost ' + response.status) | |
| ).catch( | |
| error => { | |
| postMessage('Connection Lost ' + error.message); | |
| } | |
| ); | |
| } | |
| const start = function (link) { | |
| fetchWithTimeout(link, {timeout: 1000, method: 'HEAD'}); | |
| setTimeout(function () { start(link); }, 1000); | |
| } | |
| onmessage = function (e) { | |
| console.log('Worker: Message received from main script'); | |
| start(e.data) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment