Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feature] Automatically reconnect to HMR with exponential backoff #785

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion packages/wmr/src/plugins/wmr/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const strip = url => url.replace(/[?&]t=\d+/g, '');
const addTimestamp = (url, time) => url + (/\?/.test(url) ? '&' : '?') + 't=' + time;

const resolve = url => new URL(url, location.origin).href;
let ws;
let ws, connectTimer, connectDelay = 0;

/**
* @param {boolean} [needsReload] Force page to reload once it's connected
Expand All @@ -19,7 +19,9 @@ function connect(needsReload) {
ws.send(JSON.stringify(msg));
}

clearTimeout(connectTimer);
ws.addEventListener('open', () => {
connectDelay = 0;
log(`Connected to server.`);
if (needsReload) {
window.location.reload();
Expand All @@ -31,6 +33,15 @@ function connect(needsReload) {

ws.addEventListener('message', handleMessage);
ws.addEventListener('error', handleError);
ws.addEventListener('close', reconnect);
Copy link
Member

@JoviDeCroock JoviDeCroock Jul 28, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could also listen for something like focussing (or visibilitychange) the browser again. This removes the need for exponential backoff, ...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that's a great idea. Thtat's what I'm using to run my code for waking up ios wrapper app

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since the exponential dropoff with 30s limit will not solve the case for a sleep longer than 30s, but visibilitychange certainly would.

Thanks guys!

}

function reconnect() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently reconnect only gets called once, should this be called again if establishing connection in connect(false) fails?

connectDelay = Math.min(connectDelay * 2, 30000) || 500;
connectTimer = setTimeout(() => {
if (ws) ws.close();
connect(false);
}, connectDelay);
}

connect();
Expand Down