Created
April 12, 2017 15:42
-
-
Save VitorLuizC/bdcd8e0a0c27919536db03956d571bce to your computer and use it in GitHub Desktop.
Continuous 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
| 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