Search code examples
node.jsarduinohid

How do I slow done a node JS event listener?


I'm trying to use a wireless controller with my code. I'm using node HID, and currently am just trying to write some code that will output "Tap" when a button is pressed the first time and output "untap" the second time. The only problem I am facing is that a single tap will set off both if statements, because the listener event refreshes way too fast. is there any way I could slow it down?

    device.on ("data", function (data){

        if (data[4]===31&&(!pressed)){

            device.pause();
            console.log("tap");

            pressed=true;

        }

        if (data[4]===31&&(pressed)){

            device.pause();

            console.log("untap");

            pressed=false;

        }



    device.resume();
    console.log(data[4]);
    console.log(pressed);

    });

(pressed is a variable declared earlier)


Solution

  • Use else if instead. At the moment, you set pressed to true if the first if is fulfilled, but if the first if is fulfilled, then the next

    if (data[4]===31&&(pressed)){
    

    will be true because both data[4] === 31 (since the first if was fulfilled) and you just set pressed to true.

    That'll cut down the logs from tap, untap, tap, untap, tap, untap, tap, untap to tap, untap, tap, untap, but it sounds like the data event is also being fired twice on a single tap, so add a slight delay before the listener's main body can be called again:

    let lastDataCall = 0;
    device.on("data", function(data) {
      const now = Date.now();
      if (now - lastDataCall < 20) { // 20 milliseconds
        return;
      }
      lastDataCall = now;
      if (data[4] === 31) {
        device.pause();
        if (!pressed) {
          console.log("tap");
          pressed = true;
        } else if ((pressed)) {
          console.log("untap");
          pressed = false;
        }
      }
      device.resume();
      console.log(data[4]);
      console.log(pressed);
    });
    

    (if the only code you have in the data handler relates to tapping/untapping, you can trim things down by returning early if data[4] !== 31, it'll probably make the code a bit more readable)