Skip to content

Loop

Basic loops in Javascript look like:

while (hue < 100) {
// do something
...
// change condition
hue++;
}
const list [ 100, 231, 90 ];
for (const i of list) {
// Do something with each item of the list
}

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:

import { continuously } from "https://unpkg.com/ixfx/dist/flow.js"
continuously(() => {
// Do something at animation loop speed
}).start();

If you don’t want the loop to run as fast as possible, provide an Interval or a number denoting milliseconds:

const fetchData = () => { // Do something };
// Runs every minute
continuously(fetchData, { mins: 1 }).start();

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.

const job = () => { ... }
const jobLoop = continuously(job, 1000);
...
jobLoop.start(); // Starts loop, or resets it if already pending
jobLoop.cancel(); // Cancels a scheduled loop
jobLoop.interval = { secs: 5 }; // Change loop speed

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:

import { delayLoop } from "https://unpkg.com/ixfx/dist/flow.js"
for await (const o of delayLoop(1000)) {
// Do something every second
// Warning: loops forever
}
// Execution won't continue here until the loop is exited

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:

import { delayLoop } from "https://unpkg.com/ixfx/dist/flow.js"
setTimeout(async () => {
for await (const o of delayLoop(1000)) {
console.log(`!`);
}
});
// Execution continues while looped code runs in parallel
console.log(`Hello`);