delay.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Manage delayed and timed actions
  3. *
  4. * @license GPL2 (http://www.gnu.org/licenses/gpl.html)
  5. * @author Adrian Lang <lang@cosmocode.de>
  6. */
  7. /**
  8. * Provide a global callback for window.setTimeout
  9. *
  10. * To get a timeout for non-global functions, just call
  11. * delay.add(func, timeout).
  12. */
  13. var timer = {
  14. _cur_id: 0,
  15. _handlers: {},
  16. execDispatch: function (id) {
  17. timer._handlers[id]();
  18. },
  19. add: function (func, timeout) {
  20. var id = ++timer._cur_id;
  21. timer._handlers[id] = func;
  22. return window.setTimeout('timer.execDispatch(' + id + ')', timeout);
  23. }
  24. };
  25. /**
  26. * Provide a delayed start
  27. *
  28. * To call a function with a delay, just create a new Delay(func, timeout) and
  29. * call that object’s method “start”.
  30. */
  31. function Delay (func, timeout) {
  32. this.func = func;
  33. if (timeout) {
  34. this.timeout = timeout;
  35. }
  36. }
  37. Delay.prototype = {
  38. func: null,
  39. timeout: 500,
  40. delTimer: function () {
  41. if (this.timer !== null) {
  42. window.clearTimeout(this.timer);
  43. this.timer = null;
  44. }
  45. },
  46. start: function () {
  47. DEPRECATED('don\'t use the Delay object, use window.timeout with a callback instead');
  48. this.delTimer();
  49. var _this = this;
  50. this.timer = timer.add(function () { _this.exec.call(_this); },
  51. this.timeout);
  52. this._data = {
  53. _this: arguments[0],
  54. _params: Array.prototype.slice.call(arguments, 2)
  55. };
  56. },
  57. exec: function () {
  58. this.delTimer();
  59. this.func.call(this._data._this, this._data._params);
  60. }
  61. };