debounce method

void debounce({
  1. String? uniqueKey,
})

Debounce the function call to prevent it from being called too frequently.

If called multiple times within the timeout period, only the last call will be executed after the timeout. The first call executes immediately, and subsequent calls within the debounce period are ignored until the timeout expires.

uniqueKey: An optional key to uniquely identify the debounced function.

Implementation

void debounce({String? uniqueKey}) {
  // Use the provided uniqueKey or fallback to the hash code of the target function.
  String key = uniqueKey ?? target.hashCode.toString();
  // Cancel any existing timer for this key.
  Timer? timer = _funcDebounce[key];
  timer?.cancel();
  // Start a new timer for the debounce period.
  timer = Timer(Duration(milliseconds: timeout), () {
    // Remove and cancel the timer when the timeout completes.
    Timer? t = _funcDebounce.remove(key);
    t?.cancel();
    // Call the target function.
    target?.call();
  });
  // Store the new timer in the map.
  _funcDebounce[key] = timer;
}