Skip to content

Instantly share code, notes, and snippets.

@sboyina
Last active July 31, 2020 06:55
Show Gist options
  • Save sboyina/dc8d14f9447ee4603e37ee5b018af5db to your computer and use it in GitHub Desktop.
Save sboyina/dc8d14f9447ee4603e37ee5b018af5db to your computer and use it in GitHub Desktop.
Watches whether the url is healthy (200)
(() => {
let endWatch = () => {};
const log = (msg, color) => {
console.log('%c Jon Snow %c ' + msg, 'color: white;background: black;padding: 5px 2px;', 'color:' + color);
};
log('Hello there.', 'green');
window.JONSNOW = {
'watch': (url, interval) => {
window['JONSNOW'] && window.JONSNOW.end();
interval = interval || 60 * 1000;
if (interval < 60 * 1000) {
log('its too frequent. Such a short span of of life', 'orange');
}
const intervalId = setInterval(() => {
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", () => {
if (oReq.status === 200) {
log('it is alive', 'orange')
} else {
log('it might be dead', 'red')
}
});
oReq.open("GET", url);
oReq.send();
}, interval);
endWatch = () => {
clearInterval(intervalId);
log('My watch has ended.', 'red');
window.removeEventListener('beforeunload', endWatch);
};
window.addEventListener('beforeunload', endWatch);
log('My watch has started.', 'green');
return endWatch;
},
'end': () => {
endWatch()
}
};
return window.JONSNOW;
})().watch('url_to_check', 2 * 60 * 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment