fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <chrono>
  4. #include <thread>
  5. #include <mutex>
  6. #include <condition_variable>
  7.  
  8. class Debouncer {
  9. public:
  10. Debouncer(std::chrono::milliseconds debounceTime)
  11. : debounceTime(debounceTime), lastCallTime(std::chrono::steady_clock::now()), active(false) {}
  12.  
  13. void call(std::function<void()> func) {
  14. std::unique_lock<std::mutex> lock(mutex);
  15. lastCallTime = std::chrono::steady_clock::now();
  16. if (!active) {
  17. active = true;
  18. std::thread([this, func]() {
  19. std::this_thread::sleep_for(debounceTime);
  20. std::unique_lock<std::mutex> lock(mutex);
  21. auto now = std::chrono::steady_clock::now();
  22. if (now - lastCallTime >= debounceTime) {
  23. func();
  24. active = false;
  25. } else {
  26. // Wait for the remaining time and then call the function
  27. std::this_thread::sleep_for(debounceTime - (now - lastCallTime));
  28. func();
  29. active = false;
  30. }
  31. }).detach();
  32. }
  33. }
  34.  
  35. private:
  36. std::chrono::milliseconds debounceTime;
  37. std::chrono::steady_clock::time_point lastCallTime;
  38. bool active;
  39. std::mutex mutex;
  40. };
  41.  
  42. // Example usage:
  43. void exampleFunction() {
  44. static int counter = 0;
  45. std::cout << "Function called " << ++counter << std::endl;
  46. }
  47.  
  48. int main() {
  49. Debouncer debouncer(std::chrono::milliseconds(100));
  50.  
  51. // Simulating rapid calls
  52. for (int i = 0; i < 32; ++i) {
  53. debouncer.call(exampleFunction);
  54. std::this_thread::sleep_for(std::chrono::milliseconds(30));
  55. }
  56.  
  57. // Give some time for debouncer to process
  58. std::this_thread::sleep_for(std::chrono::milliseconds(2000));
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Function called 1
Function called 2
Function called 3
Function called 4
Function called 5
Function called 6
Function called 7
Function called 8