// Created on savesnippets.com ยท https://savesnippets.com/gXbJwJSBydT7Cz function longPoll(url, onData, { interval = 3000, maxBackoff = 30_000 } = {}) { let delay = interval; let stopped = false; async function poll() { if (stopped) return; try { const res = await fetch(url); if (res.ok) { onData(await res.json()); delay = interval; } } catch (err) { console.warn('Long poll error:', err); delay = Math.min(delay * 2, maxBackoff); } if (!stopped) setTimeout(poll, delay); } poll(); return { stop: () => { stopped = true; } }; } // Usage const poller = longPoll('/api/notifications', (data) => { console.log('New notification:', data); }); // Later: poller.stop();