js承诺,取消超时

时间:2016-11-09 12:27:43

标签: javascript promise cancellation

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

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

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

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

2 个答案:

答案 0 :(得分:1)

也许是这样的事情?



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" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

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();
}