Loop
Basic loops in Javascript look like:
However, they don’t let you repeat with some timing between iteration. ixfx has two functions to help with timed loops:
- continuously: Useful for a ‘main loop’, can be controlled
- delayLoop: A ‘for’ loop with some delay between iterations
Continuously
Flow.continuously is a controllable loop. It can be started, stopped and reset, with timing changed dynamically.
As it runs, it keeps track of how many times it has looped, which can be useful for example to do something over time. The callback function can also exit the loop if it returns false.
By default, it runs at animation speed, useful for updating a canvas:
If you don’t want the loop to run as fast as possible, provide an Interval or a number denoting milliseconds:
Control
Note the use of start
to start the loop. This allows you setup the loop once, and trigger it from different places. If start
is called while already running, the timer is reset. cancel
stops a loop that is scheduled to run.
It’s possible to check the status of a Type Flow.Continuously instance with its runState
property. It returns a string, one of:
- “idle”: not yet started, or has been stopped.
- “scheduled”: started, waiting to run the callback.
- “running”: currently executing the callback.
Delayed loop
If you don’t need to adjust the loop or control it from other parts of your code, Flow.delayLoop might be what you need. It is an async generator which runs indefinitely and has a simple syntax:
Note the use of for await is important here. Use break
when you want to exit the loop.
Using for await
means that code won’t continue running until the loop finishes. If you want some code running in a delay loop whilst also continuing execution, you can use this (somewhat awkward) technique: