Debounce.h 681 B

1234567891011121314151617181920212223242526272829
  1. /*
  2. * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibCore/Timer.h>
  8. namespace Core {
  9. template<typename TFunction>
  10. auto debounce(int timeout, TFunction function)
  11. {
  12. RefPtr<Core::Timer> timer;
  13. return [=]<typename... T>(T... args) mutable {
  14. auto apply_function = [=] { function(args...); };
  15. if (timer) {
  16. timer->stop();
  17. timer->on_timeout = move(apply_function);
  18. } else {
  19. timer = Core::Timer::create_single_shot(timeout, move(apply_function)).release_value_but_fixme_should_propagate_errors();
  20. }
  21. timer->start();
  22. };
  23. }
  24. }