DEV Community

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

Posted on • Edited on • Originally published at oliverjumpertz.com

3 1

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 {
    promise,
    cancel() {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
        _reject();
        _reject = null;
      }
    }
  };
};
Enter fullscreen mode Exit fullscreen mode

Usage

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");
delayed.promise
  .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.
delayed.cancel();
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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay