How can I use AbortController to cancel a Discord.js collector or timeout gracefully?
0 reputation · 06 Oct 2023, 16:12 UTC
When building a Discord.js command that creates a MessageCollector with a set time limit, I sometimes need to stop the collector early because an external condition occurs, such as a button interaction that indicates the user no longer wants to wait. The collector’s internal timeout relies on Node.js timers, and the timers/promises API offers an AbortSignal option to cancel the scheduled timeout.
Although AbortController provides an abort() method to signal cancellation, it is not obvious how to forward its signal to the collector’s timeout mechanism so that the collector stops cleanly without leaving pending timers or causing unhandled promise rejections. I want to understand the correct way to integrate the signal and what guarantees the library provides regarding cleanup.
Questions: How do I attach the AbortSignal to the MessageCollector’s timeout? What is the state of the collector’s promise after an abort? Is any manual cleanup required to prevent lingering timers?