Skip to content

Commit 80da9cb

Browse files
authored
automatic reconnect (#1127)
1 parent 0b9a67f commit 80da9cb

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

src/client/preview.js

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,13 @@ import {enableCopyButtons} from "./pre.js";
44

55
export * from "./index.js";
66

7+
let minReopenDelay = 1000;
8+
let maxReopenDelay = 30000;
9+
let reopenDelay = minReopenDelay;
10+
let reopenDecay = 1.1; // exponential backoff factor
11+
712
export function open({hash, eval: compile} = {}) {
13+
let opened = false;
814
const socket = new WebSocket(
915
Object.assign(new URL("/_observablehq", location.href), {
1016
protocol: location.protocol === "https:" ? "wss" : "ws"
@@ -13,6 +19,8 @@ export function open({hash, eval: compile} = {}) {
1319

1420
socket.onopen = () => {
1521
console.info("socket open");
22+
opened = true;
23+
reopenDelay = minReopenDelay;
1624
send({type: "hello", path: location.pathname, hash});
1725
};
1826

@@ -123,12 +131,10 @@ export function open({hash, eval: compile} = {}) {
123131
}
124132
};
125133

126-
socket.onerror = (error) => {
127-
console.error(error);
128-
};
129-
130134
socket.onclose = () => {
131-
console.info("socket close");
135+
if (opened) console.info("socket close");
136+
reopenDelay = Math.min(maxReopenDelay, reopenDelay * reopenDecay); // exponential backoff
137+
setTimeout(() => open({hash, eval: compile}), reopenDelay);
132138
};
133139

134140
function indexCells(map, node) {

0 commit comments

Comments
 (0)