/static/scripts/timer.js

https://bitbucket.org/cistrome/cistrome-harvard/ · JavaScript · 74 lines · 56 code · 7 blank · 11 comment · 7 complexity · a0432d51e5040c813ca8a4789c704b1a MD5 · raw file

  1. // source/credits: "Algorithm": http://www.codingforums.com/showthread.php?s=&threadid=10531
  2. // The constructor should be called with
  3. // the parent object (optional, defaults to window).
  4. function Timer(){
  5. this.obj = (arguments.length)?arguments[0]:window;
  6. return this;
  7. }
  8. // The set functions should be called with:
  9. // - The name of the object method (as a string) (required)
  10. // - The millisecond delay (required)
  11. // - Any number of extra arguments, which will all be
  12. // passed to the method when it is evaluated.
  13. Timer.prototype.setInterval = function(func, msec){
  14. var i = Timer.getNew();
  15. var t = Timer.buildCall(this.obj, i, arguments);
  16. Timer.set[i].timer = window.setInterval(t,msec);
  17. return i;
  18. }
  19. Timer.prototype.setTimeout = function(func, msec){
  20. var i = Timer.getNew();
  21. Timer.buildCall(this.obj, i, arguments);
  22. Timer.set[i].timer = window.setTimeout("Timer.callOnce("+i+");",msec);
  23. return i;
  24. }
  25. // The clear functions should be called with
  26. // the return value from the equivalent set function.
  27. Timer.prototype.clearInterval = function(i){
  28. if(!Timer.set[i]) return;
  29. window.clearInterval(Timer.set[i].timer);
  30. Timer.set[i] = null;
  31. }
  32. Timer.prototype.clearTimeout = function(i){
  33. if(!Timer.set[i]) return;
  34. window.clearTimeout(Timer.set[i].timer);
  35. Timer.set[i] = null;
  36. }
  37. // Private data
  38. Timer.set = new Array();
  39. Timer.buildCall = function(obj, i, args){
  40. var t = "";
  41. Timer.set[i] = new Array();
  42. if(obj != window){
  43. Timer.set[i].obj = obj;
  44. t = "Timer.set["+i+"].obj.";
  45. }
  46. t += args[0]+"(";
  47. if(args.length > 2){
  48. Timer.set[i][0] = args[2];
  49. t += "Timer.set["+i+"][0]";
  50. for(var j=1; (j+2)<args.length; j++){
  51. Timer.set[i][j] = args[j+2];
  52. t += ", Timer.set["+i+"]["+j+"]";
  53. }}
  54. t += ");";
  55. Timer.set[i].call = t;
  56. return t;
  57. }
  58. Timer.callOnce = function(i){
  59. if(!Timer.set[i]) return;
  60. eval(Timer.set[i].call);
  61. Timer.set[i] = null;
  62. }
  63. Timer.getNew = function(){
  64. var i = 0;
  65. while(Timer.set[i]) i++;
  66. return i;
  67. }