0

I am trying to achieve a cancelable delay in an async function like so:

async function update() {
    try {
        await delay(1000);
        // if not cancelled, keep going
    } catch(error) {
        // if cancelled, do nothing
    }
    try {
        await doJob();
    } catch(error) {
        // if error from doJob, handle it
    }
}

I know that await new Promise(resolve => setTimeout(resolve, 1000)) can be used to wait the delay but it cannot be cancelled.

I also tried that:

let delayTID = null;
setTimeout(() => {
  clearTimeout(delayTID);
}, 1000);
await new Promise(function (resolve) {
  delayTID = setTimeout(resolve, 2000);
});

But it does not work because the resolve is never called and the last await never ends.

Thank you in advance!

gcomte
  • 51
  • 1
  • 7

0 Answers0