index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. var TIMEOUT_MAX = 2147483647; // 2^31-1
  2. exports.setTimeout = function(listener, after) {
  3. return new Timeout(listener, after)
  4. }
  5. exports.setInterval = function(listener, after) {
  6. return new Interval(listener, after)
  7. }
  8. exports.clearTimeout = function(timer) {
  9. if (timer) timer.close()
  10. }
  11. exports.clearInterval = exports.clearTimeout
  12. exports.Timeout = Timeout
  13. exports.Interval = Interval
  14. function Timeout(listener, after) {
  15. this.listener = listener
  16. this.after = after
  17. this.unreffed = false
  18. this.start()
  19. }
  20. Timeout.prototype.unref = function() {
  21. if (!this.unreffed) {
  22. this.unreffed = true
  23. this.timeout.unref()
  24. }
  25. }
  26. Timeout.prototype.ref = function() {
  27. if (this.unreffed) {
  28. this.unreffed = false
  29. this.timeout.ref()
  30. }
  31. }
  32. Timeout.prototype.start = function() {
  33. if (this.after <= TIMEOUT_MAX) {
  34. this.timeout = setTimeout(this.listener, this.after)
  35. } else {
  36. var self = this
  37. this.timeout = setTimeout(function() {
  38. self.after -= TIMEOUT_MAX
  39. self.start()
  40. }, TIMEOUT_MAX)
  41. }
  42. if (this.unreffed) {
  43. this.timeout.unref()
  44. }
  45. }
  46. Timeout.prototype.close = function() {
  47. clearTimeout(this.timeout)
  48. }
  49. function Interval(listener, after) {
  50. this.listener = listener
  51. this.after = this.timeLeft = after
  52. this.unreffed = false
  53. this.start()
  54. }
  55. Interval.prototype.unref = function() {
  56. if (!this.unreffed) {
  57. this.unreffed = true
  58. this.timeout.unref()
  59. }
  60. }
  61. Interval.prototype.ref = function() {
  62. if (this.unreffed) {
  63. this.unreffed = false
  64. this.timeout.ref()
  65. }
  66. }
  67. Interval.prototype.start = function() {
  68. var self = this
  69. if (this.timeLeft <= TIMEOUT_MAX) {
  70. this.timeout = setTimeout(function() {
  71. self.listener()
  72. self.timeLeft = self.after
  73. self.start()
  74. }, this.timeLeft)
  75. } else {
  76. this.timeout = setTimeout(function() {
  77. self.timeLeft -= TIMEOUT_MAX
  78. self.start()
  79. }, TIMEOUT_MAX)
  80. }
  81. if (this.unreffed) {
  82. this.timeout.unref()
  83. }
  84. }
  85. Interval.prototype.close = function() {
  86. Timeout.prototype.close.apply(this, arguments)
  87. }