intervalMenager.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. module.exports = class intervalMenager {
  2. constructor() {
  3. this.intervalId = null;
  4. this.function = function () {
  5. console.log("Somethink should be here");
  6. };
  7. this.interval = 1000;
  8. this.id = 0;
  9. this.lastInterval = null;
  10. return this;
  11. }
  12. setFunction(fn){
  13. if(typeof fn !== "function"){
  14. throw new TypeError("fn should be a function");
  15. }
  16. this.function = fn;
  17. return this;
  18. }
  19. setInterval(int){
  20. if (typeof int !== "number") {
  21. throw new TypeError("int should be a number");
  22. }
  23. this.interval = int;
  24. return this;
  25. }
  26. getLast(){
  27. if (this.lastInterval === null) {
  28. return 0;
  29. }
  30. return (new Date()) - this.lastInterval;
  31. }
  32. start(){
  33. if (this.intervalId === null) {
  34. var fun = function () {
  35. self.function(++self.id);
  36. self.lastInterval = new Date();
  37. };
  38. var self = this;
  39. this.intervalId = setInterval(fun, this.interval);
  40. setTimeout(fun, 1);
  41. return this;
  42. }else{
  43. throw new Error("Interval already started");
  44. }
  45. }
  46. stop(){
  47. if(this.intervalId !== null){
  48. clearInterval(this.intervalId);
  49. this.intervalId = null;
  50. return this;
  51. }else{
  52. throw new Error("No interval to stop");
  53. }
  54. }
  55. };