Skip to content

Instantly share code, notes, and snippets.

@Kuzmenko-Pavel
Created November 9, 2022 19:05
Show Gist options
  • Select an option

  • Save Kuzmenko-Pavel/eefdb66969d8473cf669b5711a4182c7 to your computer and use it in GitHub Desktop.

Select an option

Save Kuzmenko-Pavel/eefdb66969d8473cf669b5711a4182c7 to your computer and use it in GitHub Desktop.
web worker check connection
<!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>
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