art-standard-lib
Version:
The Standard Library for JavaScript that aught to be.
48 lines (37 loc) • 1.42 kB
text/coffeescript
{Promise} = require './Promise'
{currentSecond} = require './Time'
{timeout} = require './AsyncExtensions'
module.exports = class ReschedulableTimer
constructor: ->
= 0
###
every time you call timeout it effectively cancels all previously pending timeouts
leaving only this, new timeout active.
In actuality, the repvious timeouts complete at some point, but their 'actions' are skipped.
OUT:
Promise.then ->
The result of the next-completed timeout.
Note:
If no additional calls to timeout are made within your ms, then
this will be the result of your action.
However, if another timeout is triggered before ms expires, the result
will be the result of the action passed in then.
###
timeout: (ms, action) ->
actionCount = += 1
# console.log setup: {actionCount, action: action.toString()}
timeout ms, =>
# console.log {actionCount, , action: action.toString(), go: == actionCount}
if == actionCount
{reject, resolve} = @
Promise.then -> action()
.catch reject
.then resolve
cancel: ->
= = = null
++
_getPendingPromise: ->
?= new Promise (, ) =>