DEV Community

Cover image for JavaScript Quick Tip: Create A Cancelable Promise Delay
Oliver Jumpertz
Oliver Jumpertz

Posted on • Updated on • Originally published at

JavaScript Quick Tip: Create A Cancelable Promise Delay

You might see the need to wait for a short period before you do a certain action from time to time. JavaScript has setTimeout for this, and it works perfectly fine. But what if you want to work with Promises and perhaps even async/await?

setTimeout breaks this pattern because it takes a callback. But gladly, we can combine both to create a delayed Promise you can await if you want.

The Code

const delay = (delay, value) => {
  let timeout;
  let _reject;
  const promise = new Promise((resolve, reject) => {
    _reject = reject;
    timeout = setTimeout(resolve, delay, value);
  return {
    cancel() {
      if (timeout) {
        timeout = null;
        _reject = null;
Enter fullscreen mode Exit fullscreen mode


You can then use it like this afterward:

const delayed = delay(5000, "This value is returned by the promise");

// This await only returns after at least 5 seconds.
// Execution is halted before it continues after the
// Promise resolves.
const value = await delayed.promise;

// more operations...
Enter fullscreen mode Exit fullscreen mode

And if you want to take advantage of being able to cancel it, you can use it like this:

const delayed = delay(5000, "value");
  .then((value) => console.log(value))
  .catch(() => console.error("Rejected"));

// This will be executed before the promise fires. 
// Thus, the Promise is canceled and
// the catch is executed.
Enter fullscreen mode Exit fullscreen mode

The Whole Tip As An Image

If you like visual content more, or if you simply want to store it for later, I put all this into one single image for you. I hope you like it!

A picture showcasing the above code

Before You Leave

If you would love to read even more content like this, feel free to visit me on Twitter or on LinkedIn.

Top comments (0)