Watchdog Timer Aborts Stalled Tasks

Feed a watchdog timer after every progress step; when work stalls past its budget the timer aborts the task through AbortController with a stall reason.

JavascriptResilience

Code

javascriptsnippet
58 lines
// Watchdog: a timer that must be fed after every progress step; if work
// stalls past the budget, the timer aborts the task with a stall reason
function createWatchdog(timeoutMs, onStall) {
  let timer = null;
  const controller = new AbortController();
  return {
    signal: controller.signal,
    feed() {
      if (timer !== null) clearTimeout(timer);
      timer = setTimeout(() => {
        controller.abort(new Error('stalled past ' + timeoutMs + 'ms budget'));
        onStall();
      }, timeoutMs);
    },
    stop() {
      if (timer !== null) clearTimeout(timer);
      timer = null;
    },
  };
}

function sleep(ms, signal) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) {
      reject(signal.reason);
      return;
    }
    const timer = setTimeout(resolve, ms);
    signal?.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(signal.reason);
    }, { once: true });
  });
}

async function main() {
  // healthy task: feeds the watchdog on every step and finishes cleanly
  const fed = createWatchdog(100, () => console.log('fed task: watchdog fired'));
  fed.feed();
  await sleep(40, fed.signal);
  fed.feed();
  await sleep(40, fed.signal);
  fed.stop();
  console.log('fed task: completed cleanly');

  // stalled task: never feeds again, so the watchdog aborts it
  const stalled = createWatchdog(80, () => console.log('stalled task: watchdog fired'));
  stalled.feed();
  try {
    await sleep(500, stalled.signal);
    console.log('stalled task: never reached');
  } catch (err) {
    console.log('stalled task: aborted ->', err.message);
  }
  stalled.stop();
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

fed task: completed cleanly
stalled task: watchdog fired
stalled task: aborted -> stalled past 80ms budget

How it works

Structurally, expect the functions createWatchdog, sleep and main and nothing else.

The async parts await their results, which keeps ordering predictable.

Returns a newly built value, leaving the inputs as they were.

Putting it to use

The entry-point signature is function createWatchdog(timeoutMs, onStall)

Output lines are prefixed (fed task: completed cleanly, stalled task: watchdog fired, stalled task: aborted ->), making each step’s effect easy to spot.

Running the file executes main, which drives createWatchdog and sleep in order.

Core lines

return new Promise((resolve, reject) => {
  if (signal?.aborted) {
    reject(signal.reason);
    return;
  }
  const timer = setTimeout(resolve, ms);
  signal?.addEventListener('abort', () => {
    clearTimeout(timer);
    reject(signal.reason);
  }, { once: true });
});
const controller = new AbortController();
await sleep(500, stalled.signal);

Interactive Tools for This Topic

FAQ

Does `createWatchdog` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
What does Watchdog Timer Aborts Stalled Tasks print when run?
Running the file directly is enough — expect labeled output lines such as `fed task: completed cleanly`, `stalled task: watchdog fired`, `stalled task: aborted ->`.