Pause polling in a hidden tab

Do not waste requests when nobody is looking.

AJAX · Pause polling in a hidden tabIntermediate
let timer = null;

async function refresh() {
  if (document.hidden) return;
  try {
    const data = await (await fetch('/api/notifications')).json();
    document.getElementById('badge').textContent = data.items.length;
  } catch (e) {}
}

document.addEventListener('visibilitychange', function () {
  if (!document.hidden) refresh();                    // catch up immediately
});

timer = setInterval(refresh, 10000);
refresh();
pollingvisibilitychangebattery