| 142 | * @author Jim Chen |
| 143 | */ |
| 144 | export class Timer { |
| 145 | private _repeatCount:number = 0; |
| 146 | private _delay:number = 0; |
| 147 | private _microtime:number = 0; |
| 148 | private _timer:number = -1; |
| 149 | private _listeners:Array<Function> = []; |
| 150 | private _complete:Array<Function> = []; |
| 151 | public currentCount:number = 0; |
| 152 | |
| 153 | constructor(delay:number, repeatCount:number = 0) { |
| 154 | this._delay = delay; |
| 155 | this._repeatCount = repeatCount; |
| 156 | } |
| 157 | |
| 158 | set isRunning(b:boolean) { |
| 159 | __trace('Timer.isRunning is read-only', 'warn'); |
| 160 | } |
| 161 | |
| 162 | get isRunning():boolean { |
| 163 | return this._timer >= 0; |
| 164 | } |
| 165 | |
| 166 | public start():void { |
| 167 | if (!this.isRunning) { |
| 168 | var lastTime = Date.now(); |
| 169 | var self = this; |
| 170 | this._timer = setInterval( () => { |
| 171 | var elapsed = Date.now() - lastTime; |
| 172 | self._microtime += elapsed; |
| 173 | if (self._microtime > self._delay) { |
| 174 | self._microtime -= self._delay; |
| 175 | self.currentCount++; |
| 176 | self.dispatchEvent('timer'); |
| 177 | } |
| 178 | lastTime = Date.now(); |
| 179 | if (self._repeatCount > 0 && |
| 180 | self._repeatCount <= self.currentCount) { |
| 181 | self.stop(); |
| 182 | self.dispatchEvent('timerComplete'); |
| 183 | } |
| 184 | }, 20); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | public stop():void { |
| 189 | if (this.isRunning) { |
| 190 | clearInterval(this._timer); |
| 191 | this._timer = -1; |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | public reset():void { |
| 196 | this.stop(); |
| 197 | this.currentCount = 0; |
| 198 | this._microtime = 0; |
| 199 | } |
| 200 | |
| 201 | public addEventListener(type:string, listener:Function):void { |
nothing calls this directly
no outgoing calls
no test coverage detected