intervalMenager.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. return new Date() - this.lastInterval();
  28. }
  29. start(){
  30. if (this.intervalId === null) {
  31. var self = this;
  32. this.intervalId = setInterval(function () {
  33. self.function(++self.id);
  34. self.lastInterval = new Date();
  35. }, this.interval);
  36. return this;
  37. }else{
  38. throw new Error("Interval already started");
  39. }
  40. }
  41. stop(){
  42. if(this.intervalId !== null){
  43. clearInterval(this.intervalId);
  44. this.intervalId = null;
  45. return this;
  46. }else{
  47. throw new Error("No interval to stop");
  48. }
  49. }
  50. };