index.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. exports.every = function(str) {
  2. return new Every(str);
  3. };
  4. /*
  5. Time map
  6. */
  7. var time = {
  8. millisecond: 1,
  9. second: 1000,
  10. minute: 60000,
  11. hour: 3600000,
  12. day: 86400000
  13. };
  14. for (var key in time) {
  15. if (key === 'millisecond') {
  16. time.ms = time[key];
  17. } else {
  18. time[key.charAt(0)] = time[key];
  19. }
  20. time[key + 's'] = time[key];
  21. }
  22. /*
  23. Every constructor
  24. */
  25. function Every(str) {
  26. this.count = 0;
  27. var m = parse(str);
  28. if (m) {
  29. this.time = Number(m[0]) * time[m[1]];
  30. this.type = m[1];
  31. }
  32. }
  33. Every.prototype.do = function(cb) {
  34. if (this.time) {
  35. this.interval = setInterval(callback, this.time);
  36. }
  37. var that = this;
  38. function callback() {
  39. that.count++;
  40. cb.call(that);
  41. }
  42. return this;
  43. };
  44. Every.prototype.stop = function() {
  45. if (this.interval) {
  46. clearInterval(this.interval);
  47. delete this.interval;
  48. }
  49. return this;
  50. };
  51. /*
  52. Convert string to milliseconds
  53. ms, millisecond(s)?
  54. s, second(s)?
  55. m, minute(s)?
  56. h, hour(s)?
  57. d, day(s)?
  58. */
  59. var reg = /^\s*(\d+(?:\.\d+)?)\s*([a-z]+)\s*$/;
  60. function parse(str) {
  61. var m = str.match(reg);
  62. if (m && time[m[2]]) {
  63. return m.slice(1);
  64. }
  65. return null;
  66. }