Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Created April 12, 2017 15:42
Show Gist options
  • Save VitorLuizC/bdcd8e0a0c27919536db03956d571bce to your computer and use it in GitHub Desktop.
Save VitorLuizC/bdcd8e0a0c27919536db03956d571bce to your computer and use it in GitHub Desktop.
Continuous check connection
const available = (function () {
const url = `//${location.hostname}:${location.port}/ok`
const available = {
isAvailable: false,
onChange: () => undefined
}
check()
function check() {
fetch(`${url}/?cache=${~~(Math.random() * 0x10000)}`, { method: 'get' })
.then(({status}) => {
let isAvailable = status >= 200 && (status < 300 || status === 304)
update(isAvailable)
setTimeout(check, (isAvailable ? 5 : 20) * 1000)
})
.catch(error => {
update(false)
setTimeout(check, 20 * 1000)
})
}
function update(isAvailable) {
if (available.isAvailable === isAvailable)
return;
available.onChange(isAvailable)
available.isAvailable = isAvailable
}
return available
} ())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment