js Promise,取消超时

js Promise, cancel timeout

目前我正在使用脚本在执行下一个操作之前为我的函数设置 3 秒的超时。

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

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

现在我想找到一种方法来提前结束 3 秒超时,例如通过执行鼠标单击。我将如何实施它?

作为一个想法,也许你可以这样做:

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

sleep(3000).then(function()
{
    // next action
});
function myStopFunction() {
    clearTimeout(timeout);
    myResolver();
}

也许是这样的?

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" />