Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debounce in C++

I'm trying to write a dummy debounce function in c++. Here is what I have written:

 #include <bits/stdc++.h>
    using namespace std;
    using namespace chrono;
    function<void(int)>debounce(function<void(void)>&f , int period){
        function<void(int)> fn = [&](int per){
            static auto init_time = high_resolution_clock::now();
            auto final_time = high_resolution_clock::now();
            if ( duration_cast<milliseconds>(final_time - init_time).count() > per){
                f();
            }
            init_time = final_time;
        };
        return fn;
    }
    int main(void){
        int x = 0;
        function<void(void) > f = [&x](void){
            x++;
        };
        function<void(int)> xdf = debounce(f , 30);
        std::this_thread::sleep_for(milliseconds(300));
        xdf(300);
        xdf(300);
        std::this_thread::sleep_for(milliseconds(300));
        xdf(300);
        if(x>=3 || x != 2){
            cout << "Debounce failed" << '\n'; 
        }else {
            cout << "Successful" << '\n'; 
        }
        return 0;
    }

But this doesn't work fine. Is there any way so that I don't have to pass the time limit to xdf function? Maybe this is not the correct code. Can you give some other ideas to implement or correct this one?

like image 525
Amit Kumar Avatar asked Jul 03 '26 06:07

Amit Kumar


1 Answers

A convertion word to word of the go implementation you linked.

#include <bits/stdc++.h>
#include <stdexcept>
using namespace std;
using namespace chrono;

function<void()> Debounced(function<void()>&f , int period){
    static auto created = high_resolution_clock::now();
    // "=" allow to pass by copy all used variables (created and period)
    // "&f" allow to pass by reference f variable
    function<void()> fn = [=,&f](){
        auto now = high_resolution_clock::now();
        if (duration_cast<milliseconds>(now - created).count() > period){
            f();
        }
    };
    return fn;
}

int main(void){
    int x = 0;
    function<void()> f = [&x](){
        x++;
    };

    auto dbf = Debounced(f, 500);
    for (int i = 0; i < 10; ++i) {
      dbf();
    }
    if (x != 0) {
      throw std::runtime_error("Expected x not to change since it's debounced for 500ms");
    }
    std::this_thread::sleep_for(milliseconds(500));
    for (int i = 0; i < 10; ++i) {
      dbf();
    }
    if (x != 10) {
      throw std::runtime_error("Expected x to be incremented 10 times");
    }
}
like image 174
Erwan Avatar answered Jul 04 '26 20:07

Erwan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!