Last active
December 16, 2015 00:59
-
-
Save toruta39/5351368 to your computer and use it in GitHub Desktop.
StepAction helps to get rid of nesting setTimeout
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
# StepAction helps to get rid of nesting setTimeout | |
# | |
# Function.prototype.bind feature is used. | |
# Only support IE9+ for now | |
class StepAction | |
constructor: (@steps, @initDelay) -> | |
@_timer = null | |
@_onStep = 0 | |
@_timer = setTimeout (-> @play()).bind(@), if @initDelay then @initDelay else 0 | |
next: (timeout) -> | |
clearTimeout @_timer | |
@_timer = setTimeout @steps[++@_onStep].bind(@), timeout | |
play: -> | |
clearTimeout @_timer | |
@_timer = setTimeout @steps[0].bind(@), 0 | |
fin: -> | |
clearTimeout @_timer | |
# Demo | |
new StepAction [ | |
-> | |
console.log 'Step1: 1000' | |
@next 1000 | |
-> | |
console.log 'Step2: 100' | |
@next 100 | |
-> | |
console.log 'Step3: last' | |
@fin() | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment