Timing utilities
How to trigger actions after a delay or repeatedly.
Delay
Use Utils.delay()
to trigger an action after a certain amount of time has passed.
The utility takes two arguments: the duration of the delay (in seconds) and a function ->
containing the actions you want to execute.
Utils.delay 2, ->
print "Hello."
» "Hello." # appears after 2 seconds
Alternatively, when you use an existing function (or method) that doesn’t require parameters, you can just add it as the second argument:
Utils.delay 2, anAnimationObject.start
(This way you’re pasting in the whole function, so you don’t need to call it by adding ()
.)
Of course, you can also nest them, to have delays after delays.
print "Hello."
Utils.delay 2.2, ->
print "Is there anybody in there?"
Utils.delay 4.2, ->
print "Just nod if you can hear me."
Utils.delay 4.2, ->
print "Is there anyone home?"
Interval
Use Utils.interval()
to do something every x number of seconds.
Utils.interval 1, ->
print "hello"
» "Hello." # after 1 second
» "Hello." # after 2 seconds
» "Hello." # after 3 seconds
…
Interval examples
In the Cycle utility example, the phase of the moon is changed every second:
Utils.interval 1, ->
theMoon.html = nextPhase()
And in the Random Choice example, a new animation is started every half second.
Utils.interval .5, ->
…
buildings[number].animate
x: Screen.width
options:
time: 3
curve: "linear"