Skip to content

Document new Debouncer utility #660

@hyyan

Description

@hyyan

webforj/webforj#1169

New Debouncer class added to com.webforj package for delaying action execution until activity stops.

What it does

Debouncing delays executing an action until a specified time has elapsed since the last call. Each new call resets the timer. The action only runs once the calls stop coming in.

Common use case: search-as-you-type - you don't want to search on every keystroke, only after the user stops typing.

Usage

Debouncer debounce = new Debouncer(0.3f); // 300ms delay

textField.onModify(e -> {
  debounce.run(() -> search(e.getText()));
});

Methods

  • run(Runnable) - schedule action, resets timer on each call
  • cancel() - cancel pending action
  • flush() - execute pending action immediately
  • isPending() - check if action is pending
  • getDelay() - get the delay in seconds

Notes

  • Delay is specified in seconds (float), not milliseconds
  • Runs on the UI thread via Interval - no Environment.runLater() needed
  • Action passed to run() can be different each call - the last one wins
@Route("/debounce")
public class DebouncerTestView extends Composite<FlexLayout> {

  private final FlexLayout self = getBoundComponent();
  private final TextField input = new TextField();
  private final Paragraph output = new Paragraph();
  private final Paragraph counter = new Paragraph();
  private final Debouncer debounce = new Debouncer(0.5f);
  private int count = 0;

  public DebouncerTestView() {
    self.setDirection(FlexDirection.COLUMN)
        .setStyle("padding", "20px")
        .setStyle("gap", "10px")
        .setStyle("maxWidth", "400px");

    input.setLabel("Type something (debounced 500ms)");
    input.setPlaceholder("Start typing...");
    input.onModify(e -> {
      count++;
      counter.setText("Key events: " + count);

      debounce.run(() -> {
        output.setText("Debounced: " + e.getText());
      });
    });

    output.setText("Debounced: (waiting...)");
    counter.setText("Key events: 0");

    self.add(input, counter, output);
  }
}

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions