TTLs with setInterval active sweep

Date.now() returns milliseconds since epoch. We store Date.now() + N * 1000 as the expiry. Every read checks; we also sweep periodically with setInterval.

Lazy plus active expiry in Node

Lazy: clean up on read. Active: setInterval sweep. The event loop interleaves both safely.
04-expiry/server.mjs
javascript
const STORE = new Map();
const EXPIRES = new Map(); // key -> ms-since-epoch

function checkExpired(k) {
  const ts = EXPIRES.get(k);
  if (ts !== undefined && Date.now() >= ts) {
    STORE.delete(k); EXPIRES.delete(k);
    return true;
  }
  return false;
}

Sidecar Map + checkExpired called from every read.

04-expiry/server.mjs
javascript
const sweepTimer = setInterval(() => {
  let i = 0;
  for (const k of EXPIRES.keys()) {
    if (i++ >= 100) break;
    checkExpired(k);
  }
}, 100);
sweepTimer.unref();

Active sweep. setInterval is integrated with the event loop. .unref() means the timer does not block process exit.

By default, an active timer keeps the Node process alive. .unref() says 'if I am the only thing keeping the process alive, exit anyway'. Critical for background timers.

Quiz: Quiz

Loading practice…