Schedule a delayed callback with a cancel that reports success
A mail client shows an “Undo send” toast for a few seconds before it actually sends a message. If the user clicks Undo, the send must never happen. The UI also wants to know whether the click came in time, so it can show “Message not sent” or “Too late, already sent”.
Implement scheduleCall(callback, ms, ...args). It schedules callback to run once after ms milliseconds and returns a cancel function.
const cancel = scheduleCall(callback, ms, ...args);
cancel(); // => true if this call stopped the callback, otherwise false
setTimeout. After ms milliseconds, call callback(...args) exactly once.cancel() before the callback runs stops it for good, clears the timer with clearTimeout, and returns true.cancel() returns false and does nothing if the callback has already run, or if the call was already cancelled. This includes calling cancel() from inside the callback itself.scheduleCall is independent: cancelling one never affects another.const send = (to, subject) => console.log(`sent "${subject}" to ${to}`);
const undo = scheduleCall(send, 5000, 'kai@example.com', 'Q3 plan');
// user clicks Undo after 2 seconds
undo(); // => true (nothing is ever sent)
undo(); // => false (already cancelled)
const late = scheduleCall(send, 100, 'mo@example.com', 'Hi');
// 100ms later: logs 'sent "Hi" to mo@example.com'
late(); // => false (too late, it already ran)
The tests replace setTimeout and clearTimeout with a fake clock, so call the global functions when you need them (not copies saved earlier) and do not rely on Date.now().