runloop.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. (function (Misago) {
  2. 'use strict';
  3. var RunLoop = function(_) {
  4. var self = this;
  5. this._intervals = {};
  6. var stopInterval = function(name) {
  7. if (self._intervals[name]) {
  8. window.clearTimeout(self._intervals[name]);
  9. self._intervals[name] = null;
  10. }
  11. };
  12. this.run = function(callable, name, delay) {
  13. this._intervals[name] = window.setTimeout(function() {
  14. stopInterval(name);
  15. var result = callable(_);
  16. if (result !== false) {
  17. self.run(callable, name, delay);
  18. }
  19. }, delay);
  20. };
  21. this.runOnce = function(callable, name, delay) {
  22. this._intervals[name] = window.setTimeout(function() {
  23. stopInterval(name);
  24. callable(_);
  25. }, delay);
  26. };
  27. this.stop = function(name) {
  28. for (var loop in this._intervals) {
  29. if (!name || name === loop) {
  30. stopInterval(loop);
  31. }
  32. }
  33. };
  34. };
  35. Misago.addService('runloop', {
  36. factory: function(_) {
  37. return new RunLoop(_);
  38. },
  39. destroy: function(_) {
  40. _.runloop.stop();
  41. }
  42. });
  43. }(Misago.prototype));