You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
1.0 KiB

  1. module.exports = function(callback) {
  2. var cb = function() {
  3. if (timedout || (once && count)) return;
  4. count += 1;
  5. tid && clearTimeout(tid);
  6. var args = Array.prototype.slice.call(arguments);
  7. process.nextTick(function() {
  8. if (!errback) return callback.apply(this, args);
  9. args[0] ? errback(args[0]) : callback.apply(this, args.slice(1));
  10. });
  11. }, count = 0, once = false, timedout = false, errback, tid;
  12. cb.timeout = function(ms) {
  13. tid && clearTimeout(tid);
  14. tid = setTimeout(function() {
  15. cb(new TimeoutError(ms));
  16. timedout = true;
  17. }, ms);
  18. return cb;
  19. };
  20. cb.error = function(func) { errback = func; return cb; };
  21. cb.once = function() { once = true; return cb; };
  22. return cb;
  23. };
  24. var TimeoutError = module.exports.TimeoutError = function TimeoutError(ms) {
  25. this.message = 'Specified timeout of ' + ms + 'ms was reached';
  26. Error.captureStackTrace(this, this.constructor);
  27. };
  28. TimeoutError.prototype = new Error;
  29. TimeoutError.prototype.constructor = TimeoutError;
  30. TimeoutError.prototype.name = 'TimeoutError';