jquery.timer.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * jQuery Timer Plugin (jquery.timer.js)
  3. * @version 1.0.1
  4. * @author James Brooks <jbrooksuk@me.com>
  5. * @website http://james.brooks.so
  6. * @license MIT - http://jbrooksuk.mit-license.org
  7. */
  8. (function($) {
  9. jQuery.timer = function(interval, callback, options) {
  10. // Create options for the default reset value
  11. var options = jQuery.extend({ reset: 500 }, options);
  12. var interval = interval || options.reset;
  13. if(!callback) { return false; }
  14. var Timer = function(interval, callback, disabled) {
  15. // Only used by internal code to call the callback
  16. this.internalCallback = function() { callback(self); };
  17. // Clears any timers
  18. this.stop = function() {
  19. if(this.state === 1 && this.id) {
  20. clearInterval(self.id);
  21. this.state = 0;
  22. return true;
  23. }
  24. return false;
  25. };
  26. // Resets timers to a new time
  27. this.reset = function(time) {
  28. if(self.id) { clearInterval(self.id); }
  29. var time = time || options.reset;
  30. this.id = setInterval($.proxy(this.internalCallback, this), time);
  31. this.state = 1;
  32. return true;
  33. };
  34. // Pause a timer.
  35. this.pause = function() {
  36. if(self.id && this.state === 1) {
  37. clearInterval(this.id);
  38. this.state = 2;
  39. return true;
  40. }
  41. return false;
  42. };
  43. // Resumes a paused timer.
  44. this.resume = function() {
  45. if(this.state === 2) {
  46. this.state = 1;
  47. this.id = setInterval($.proxy(this.internalCallback, this), this.interval);
  48. return true;
  49. }
  50. return false;
  51. };
  52. // Set the interval time again
  53. this.interval = interval;
  54. // Set the timer, if enabled
  55. if (!disabled) {
  56. this.id = setInterval($.proxy(this.internalCallback, this), this.interval);
  57. this.state = 1;
  58. }
  59. var self = this;
  60. };
  61. // Create a new timer object
  62. return new Timer(interval, callback, options.disabled);
  63. };
  64. })(jQuery);