Skip to content

Instantly share code, notes, and snippets.

@kojagiri1934
Last active September 7, 2020 06:42
Show Gist options
  • Save kojagiri1934/2aa2fce6736ca38e12559c4f4ba1caba to your computer and use it in GitHub Desktop.
Save kojagiri1934/2aa2fce6736ca38e12559c4f4ba1caba to your computer and use it in GitHub Desktop.
Simple Promise script that checks for Network Ready and a secondary 'readyState' (which may be set 'true' post-login or other similar situation). This is ideally used in PWA or other web applications that are offline-enabled but need to wait for network readiness before performing a one-way action (eg. game action, etc)
// Made by Chaitanya Dhareshwar for internal use. You may use this freely in your project
window.readyToSend = false; // this is made true when the socket.connect is triggered - change it to fit your usecase.
window.waitForRTS = async function waitForRTS(maxWaitms = 10000) {
console.log("wait for RTS", maxWaitms);
// some 'service' replace this with your connection confirmation/readyState
if (!socket.connected) socket.connect(); // in my case, readyToSend changes on socket connection
return await new Promise(function(resolve, reject) {
let T1 = setTimeout(() => {
clearInterval(T0);
clearTimeout(T1);
console.log("RTS failed");
return reject();
}, maxWaitms);
let T0 = setInterval(() => {
if (navigator.onLine && readyToSend) {
clearInterval(T0);
clearTimeout(T1);
console.log("RTS success");
return resolve();
}
}, 50);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment