Created
October 7, 2023 06:47
-
-
Save aztack/a7a718357b738ffb676689d1909a05de to your computer and use it in GitHub Desktop.
Test given url availability in browser wiht fetch HTTP HEAD and specific timeout
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
/** | |
* Test given url availability in browser wiht fetch HTTP HEAD and specific timeout | |
* @param url | |
*/ | |
export function probe(url: string, opt?: RequestInit & { timeout: number }) { | |
const ctrl = new AbortController(); | |
const timeout = (opt || {}).timeout || 5000; | |
const timer = setTimeout(() => ctrl.abort(), timeout); | |
return new Promise(resolve => { | |
const promise = fetch(url, { signal: ctrl.signal, method: 'HEAD', ...opt }) | |
.then(res => resolve(res.ok)) | |
.catch(() => resolve(false)); | |
ctrl.signal.addEventListener('abort', () => { | |
clearTimeout(timer); | |
resolve(false); | |
}); | |
promise.finally(() => clearTimeout(timer)); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment