Make Your Own Functions Cancellable

In Watch Snooze Stop the Routine, Saga pressed Snooze at 1.5 seconds. The blinds and the heating stopped, but the kettle kept boiling and clicked off at six seconds. Nobody had handed boilKettle() the signal, so it never heard the abort.

In this lesson, you’ll make your own device functions cancellable. You’ll give them a signal to accept and pass on, make them check it between steps, and join Snooze and the kettle’s deadline into one signal. Start with the kettle, the device that didn’t listen.

Pass the Signal on

A function can only stop for a signal it holds, so the first job is to let the caller hand one in. The timers from node:timers/promises take their signal in an options object. Your device functions can work the same way. Each one takes an options object, pulls out its signal, and passes it to the timer it waits on.

A real kettle also fills before it boils. The fill valve’s stand-in, fillKettle(), takes two seconds and has no signal parameter, because once the valve opens, it fills to the line. Many steps work like this, such as code someone else wrote or a step that can’t be stopped halfway.

Replace devices.mjs with this version. Each device now accepts { signal }, and the kettle fills for two seconds, logs that it’s heating, and boils for four:

Language: JavaScript Filename: devices.mjs
import { setTimeout as delay } from "node:timers/promises";

export async function turnOnLights({ signal } = {}) {
  await delay(1000, undefined, { signal });
  return "Lights on";
}

export async function openBlinds({ signal } = {}) {
  await delay(2000, undefined, { signal });
  throw new Error("Blinds offline");
}

export async function warmUpHeating({ signal } = {}) {
  await delay(3000, undefined, { signal });
  return "Heating on";
}

async function fillKettle() {
  await delay(2000);
}

export async function boilKettle({ signal } = {}) {
  await fillKettle();
  console.log("Kettle heating");
  await delay(4000, undefined, { signal });
  console.log("Kettle clicks off");
  return "Kettle boiled";
}

The parameter { signal } = {} destructures the options object, the way you’ve destructured parameters before. The = {} default means boilKettle() with no arguments still works. Then signal is undefined, and a timer with no signal never aborts. Each delay() call that receives a signal passes undefined as its value, since the devices return their own status.

Now change snooze.mjs from the last lesson so that every device is one of your functions, and each gets the same signal:

Language: JavaScript Filename: snooze.mjs
import {
  turnOnLights,
  openBlinds,
  warmUpHeating,
  boilKettle,
} from "./devices.mjs";

const start = Date.now();
const seconds = () => ((Date.now() - start) / 1000).toFixed(1);

const snooze = new AbortController();
const signal = snooze.signal;

setTimeout(() => {
  console.log(`${seconds()} s: Snooze pressed`);
  snooze.abort();
}, 1500);

const results = await Promise.allSettled([
  turnOnLights({ signal }),
  boilKettle({ signal }),
  openBlinds({ signal }),
  warmUpHeating({ signal }),
]);

const report = results.map((result) => {
  if (result.status === "fulfilled") {
    return result.value;
  }
  return result.reason.name;
});
console.log(`${seconds()} s:`, report);

The kettle holds the signal now, and Snooze is still pressed at 1.5 seconds, while the kettle is filling. Before you run node snooze.mjs, decide which lines the terminal shows, and when the report appears.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.