visibilitychange Pauses Work While Hidden

Listen for visibilitychange to pause background syncing while the tab is hidden and run one catch-up pass as soon as the page becomes visible again.

JavascriptResilience

Code

javascriptsnippet
34 lines
const status = document.querySelector("#sync-status");
const button = document.querySelector("#sync-now");
let syncing = false;
let wasPaused = false;

// visibilitychange 在页面隐藏/可见时各触发一次
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden") {
    // 隐藏时暂停轮询类工作,省电省配额
    wasPaused = syncing;
    status.textContent = "sync paused (tab hidden)";
  } else {
    status.textContent = "sync active";
    // 回到前台:刚才被打断的任务补跑一次
    if (wasPaused) {
      wasPaused = false;
      syncOnce();
    }
  }
});

button.addEventListener("click", () => syncOnce());

async function syncOnce() {
  if (syncing || document.visibilityState === "hidden") return;
  syncing = true;
  button.disabled = true;
  status.textContent = "syncing…";
  await new Promise((resolve) => setTimeout(resolve, 400)); // 模拟网络
  status.textContent = "synced just now";
  syncing = false;
  button.disabled = false;
}

What the code does

Everything happens inside the function syncOnce.

await marks each async boundary — nothing fires and forgets.

Watch out for

  • No package manager involved — every call resolves to a built-in API.
  • document exist only in browsers — a Node runtime has no shims for them out of the box.
  • The guard syncing || document.visibilityState === "hidden" short-circuits the flow with an early return when its condition holds.

Applying it

The primary signature is async function syncOnce()

Statements that matter

await new Promise((resolve) => setTimeout(resolve, 400)); // 模拟网络
status.textContent = "synced just now";
button.addEventListener("click", () => syncOnce());

Interactive Tools for This Topic

FAQ

Does visibilitychange Pauses Work While Hidden run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.