Created
March 11, 2012 04:58
-
-
Save wiseleyb/2015092 to your computer and use it in GitHub Desktop.
JS Timer troubles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I have this timer setup. It's the only way I could get it to work but seems very wrong... | |
# Specifically in processUserCommand if I don't clearTimeout's every time the win and max | |
# moves scenarios no longer work. Without the timer tear down the app just goes on and on | |
# after reaching max moves and/or win. | |
# Full code up on https://github.com/wiseleyb/solitr | |
# Sample app up on http://solitr.herokuapp.com/klondike-turn-three-hints | |
window.timer = new App.AutoRun | |
window.timers = [] | |
processUserCommand: (cmd) -> | |
window.timer.pause() | |
for t in window.timers | |
clearTimeout(t) | |
if @model.moves > 200 | |
alert('Game halted - too many moves') | |
return | |
@removeEventHandlers() | |
@processCommand(cmd) | |
if nextCmd = @model.nextAutoCommand() | |
window.timers.push(setTimeout (=> @processUserCommand(nextCmd)), @nextAnimationDelay(cmd)) | |
window.timer.unpause() | |
else if @model.isWon() | |
window.timers.push(setTimeout @youWin, @nextAnimationDelay(cmd)) | |
else | |
@registerEventHandlers() | |
window.timer.unpause() | |
class App.Timer | |
timers: [] | |
clearTimers: -> | |
for timer in @timers | |
timer.call @ | |
@timers = [] | |
addInterval: (callback, ms) -> | |
id = setInterval callback, ms | |
@timers.push -> | |
clearInterval id | |
id | |
addTimeout: (callback, ms) -> | |
id = setTimeout callback, ms | |
@timers.push -> | |
clearTimeout id | |
id | |
class App.AutoRun | |
# requesting: false | |
paused: false | |
constructor: -> | |
@timer = new App.Timer | |
poll: -> | |
@update() | |
@timer.addInterval (=>(@update())), 100 | |
update: -> | |
unless @requesting || @paused | |
console.log "Updating..." | |
App.gameController.hint() | |
pause: -> | |
console.log "pause request" | |
@paused = true | |
unpause: -> | |
console.log "unpause request" | |
@paused = false | |
tearDown: -> | |
@timer.clearTimers() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment