Skip to content

Instantly share code, notes, and snippets.

@venkatd
Created February 14, 2020 04:19
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save venkatd/7125882a8e86d80000ea4c2da2c2a8ad to your computer and use it in GitHub Desktop.
Save venkatd/7125882a8e86d80000ea4c2da2c2a8ad to your computer and use it in GitHub Desktop.
import 'dart:async';
class Debouncer {
final Duration delay;
Timer _timer;
Debouncer({this.delay});
run(Function action) {
_timer?.cancel();
_timer = Timer(delay, action);
}
}
// to start
final _debouncer = Debouncer(delay: Duration(milliseconds: 250));
// and later
onTextChange(String text) {
_debouncer.run(() => print(text));
}
@edTheGuy00
Copy link

Slight modification based on my preference.

class Debouncer {
  final Duration delay;
  Timer _timer;

  Debouncer({this.delay = const Duration(milliseconds: 300)});

  call(Function action) {
    _timer?.cancel();
    _timer = Timer(delay, action);
  }
}
final _debouncer = Debouncer();

_debouncer(() {
     // your action
})

@venkatd
Copy link
Author

venkatd commented Mar 13, 2020

I prefer having the delay explicitly passed in each time so the delay is obvious.

But pretty cool, didn't know about the call function!

@dcemmerson
Copy link

dcemmerson commented Dec 13, 2020

Another slight variation - it can also be convenient to return a function from the call method for the purpose of allowing us to pass arguments to the callback. For example, when listening to input coming through a stream, we can just do someStream.stream.listen(Debounce(Duration(milliseconds: 350), _fnThatTakesArgs)() with the following:

class Debounce {
  final Duration delay;
  Timer _timer;

  Debounce(this.delay);

  Function call(Function callback) {
    return (args) {
      _timer?.cancel();
      _timer = Timer(delay, () => callback(args));
    };
  }
}

@SAGARSURI
Copy link

How will you dispose of the timer?

@Hesamedin
Copy link

Hesamedin commented Oct 20, 2021

@SAGARSURI, you can have something like this and call its dispose function from your user class.

class Debouncer {
  Debouncer({this.delay = const Duration(milliseconds: 300)});

  final Duration delay;
  Timer? _timer;

  void call(void Function() callback) {
    _timer?.cancel();
    _timer = Timer(delay, callback);
  }

  void dispose() {
    _timer?.cancel(); // You can comment-out this line if you want. I am not sure if this call brings any value.
    _timer = null;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment