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