Skip to content

Timing and tasks

Giorgio Garofalo edited this page Feb 6, 2021 · 4 revisions

Chorus API makes timing and thread-related tasks easy.

  • runLater(action) executes a function on the main thread after a small delay;
  • runAsync(action) executes a function asynchronously. Note that you can't edit parts of the UI from a non-main thread and it will eventually throw an error;
  • wait(action, millis) or setTimeout(action, millis) executes a function after a given time (in milliseconds). Although it does not interrupt the main thread you can still interact with the UI;
  • cycle(action, millis, times) executes a function X times, each after a given time (in milliseconds). As for the previous function it is asynchronous but allows interacting with the UI;
  • setInterval(action, millis) executes a function for as long as the main thread is alive. Each task is delayed from the previous one by millis milliseconds.

Example:

let i = 0;
cycle(() => {
    print(++i);
}, 1000, 10);

Unrelated to timing, the listen(property, action) is worth to be put here. It takes a JavaFX property and a task as parameters. The task is called every time the property changes its value.
Example:

const textfield = new TextField();
listen(textfield.textProperty(), () => {
    print(textfield.getText());
});