main.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var nextTick = require('process/browser.js').nextTick;
  2. var apply = Function.prototype.apply;
  3. var slice = Array.prototype.slice;
  4. var immediateIds = {};
  5. var nextImmediateId = 0;
  6. // DOM APIs, for completeness
  7. exports.setTimeout = function() {
  8. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  9. };
  10. exports.setInterval = function() {
  11. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  12. };
  13. exports.clearTimeout =
  14. exports.clearInterval = function(timeout) { timeout.close(); };
  15. function Timeout(id, clearFn) {
  16. this._id = id;
  17. this._clearFn = clearFn;
  18. }
  19. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  20. Timeout.prototype.close = function() {
  21. this._clearFn.call(window, this._id);
  22. };
  23. // Does not start the time, just sets up the members needed.
  24. exports.enroll = function(item, msecs) {
  25. clearTimeout(item._idleTimeoutId);
  26. item._idleTimeout = msecs;
  27. };
  28. exports.unenroll = function(item) {
  29. clearTimeout(item._idleTimeoutId);
  30. item._idleTimeout = -1;
  31. };
  32. exports._unrefActive = exports.active = function(item) {
  33. clearTimeout(item._idleTimeoutId);
  34. var msecs = item._idleTimeout;
  35. if (msecs >= 0) {
  36. item._idleTimeoutId = setTimeout(function onTimeout() {
  37. if (item._onTimeout)
  38. item._onTimeout();
  39. }, msecs);
  40. }
  41. };
  42. // That's not how node.js implements it but the exposed api is the same.
  43. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  44. var id = nextImmediateId++;
  45. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  46. immediateIds[id] = true;
  47. nextTick(function onNextTick() {
  48. if (immediateIds[id]) {
  49. // fn.call() is faster so we optimize for the common use-case
  50. // @see http://jsperf.com/call-apply-segu
  51. if (args) {
  52. fn.apply(null, args);
  53. } else {
  54. fn.call(null);
  55. }
  56. // Prevent ids from leaking
  57. exports.clearImmediate(id);
  58. }
  59. });
  60. return id;
  61. };
  62. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  63. delete immediateIds[id];
  64. };