Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Last active December 16, 2015 19:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohayonao/5485992 to your computer and use it in GitHub Desktop.
Save mohayonao/5485992 to your computer and use it in GitHub Desktop.
ちょっとずつ実行する
class Task
constructor: (opts={})->
@_task = [].slice.call arguments, 1
@_init = opts.init ? ->{}
@_doMax = opts.do ? 1
@_timer = 0
start: ->
@_doCount = 0
@_taskIndex = 0
@_args = @_init()
next.call @
@
stop: ->
clearTimeout @_timer if @_timer != 0
@
resume: ->
clearTimeout @_timer if @_timer != 0
next.call @
@
wait: (seconds)->
@_wait = seconds
@
next = ->
if @_taskIndex >= @_task.length
@_doCount += 1
if @_doCount >= @_doMax
return @onEnd?(@_args)
@_taskIndex = 0
@_wait = 0
@_task[@_taskIndex++]?.call @, @_doCount, @_args
wait = Math.max 0, @_wait
if wait != Infinity
@_timer = setTimeout (=> next.call @), wait
else
@_timer = 0
t = new Task do:5, init: ->
word:"yes", list:["ok", "good", "awesome", "cool"]
, (count, args)->
console.log "#{count}: #{args.word}?"
@wait 250
, (count, args)->
console.log "#{count}: #{args.word}..."
setTimeout =>
@resume()
, Math.random() * 2500 + 100
@wait Infinity
, (count, args)->
console.log "#{count}: #{args.word}!!"
args.word = args.list[(Math.random() * args.list.length)|0]
@wait 1000
t.start().onEnd = ->
console.log 'end'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment