JavaScript Quick Tip: Create A Cancelable Promise Delay

JavaScript Quick Tip: Create A Cancelable Promise Delay

Oliver Jumpertz's photo
Oliver Jumpertz
·May 29, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

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;


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...

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.

The Whole Tip As An Image

If you like visual content more, or if you 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 LinkedIn.

I'd love to count you as my ever-growing group of awesome friends!

Share this