Last active
July 31, 2020 06:55
-
-
Save sboyina/dc8d14f9447ee4603e37ee5b018af5db to your computer and use it in GitHub Desktop.
Watches whether the url is healthy (200)
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
(() => { | |
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