I’m using setTimeout as a Promise. But then I cannot cancel it using clearTimeout
. THis is my code:
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
delay(1000).then(() => console.log("Done"));
But using this approach I cannot cancel timeout using clearTimeout.
I tried promisify
nestjs function but still cannot do this
2
Answers
To create a cancelable delay using Promises, you can wrap setTimeout in a way that allows you to keep track of the timeout ID and then use that ID to cancel the timeout if needed. Here’s an example of how you can do it:
You cannot cancel a promise from outside. You need to decide when and how the promise should be resolved when you create the promise. To cancel the task (in this case, the timer), pass a cancellation signal as an argument.
You don’t have to use
setTimeout
andclearTimeout
, and you don’t have to promisify them. Instead, just use the builtinsetTimeout
fromnode:timers/promises
that already provides this functionality:If you want to implement this yourself, see this answer for an example.