Search code examples
javascriptpromisecancellation

js Promise, cancel timeout


currently I am using a script to set a timeout of 3 seconds for my function before the next action is executed.

function sleep(ms)
{
    return new Promise((resolve) => setTimeout(resolve, ms));
}

sleep(3000).then(function()
{
    // next action
});

Now I want to find a way to end the 3-second timeout early e.g. by performing a mouse click. How would I go about implementing this?


Solution

  • Something like this, perhaps?

    function sleeper(ms) {
      var r;
    
      var p = new Promise(resolve => {
        r = resolve;
        setTimeout(resolve, ms);
      });
    
      return {
        skip: r,
        promise: p
      };
    }
    
    var s = sleeper(10000);
    
    s.promise.then(() => {
      console.log('Promise finished!');
    });
    
    console.log('Waiting for 10 seconds... Click the button to skip the wait.');
    
    document.getElementById('skip').addEventListener('click', s.skip);
    <input type="button" id="skip" value="Skip delay" />