Is there a version of setTimeout that returns an ES6 promise?

后端 未结 3 1537
天涯浪人
天涯浪人 2020-12-14 14:59

Similar to this question, but rather than asking about how promises work in general, I specifically want to know:

What is the standard/best way to wrap setTimeout in

3条回答
  •  忘掉有多难
    2020-12-14 15:30

    Here's how I'd implement it:

    function delay(duration, func) {
      var args = Array.prototype.slice.call(arguments, 2);
    
      return new Promise(function (resolve) {
        setTimeout(function () {
          resolve(func.apply(null, args));
        }, duration);
      });
    }
    

    (ES5-syntax intentionally chosen)

    But maybe there's a common library that already does this, or a better way to do it.

提交回复
热议问题