0

I bought an Amazon Dash button and am using the dash-button library. I have this code:

var DashButton = require("dash-button");

const DASH_BUTTON_MAC_ADDRESS = "xx:xx:xx:xx:xx:xx";

let button = new DashButton(DASH_BUTTON_MAC_ADDRESS);

console.log("ready");

let subscription = button.addListener(function(){
  let date = new Date();
  console.log(date.toTimeString() + ": button pressed!");
});

The function gets called twice sometimes in a button press. Here is the output:

ready
10:48:29 GMT+0000 (UTC): button pressed! - first button press
10:48:39 GMT+0000 (UTC): button pressed! - second button press
10:48:40 GMT+0000 (UTC): button pressed! - second button press

Is there any way to add a sort of cooldown to a function so that it can be only called every x seconds?

Jake Walker
  • 75
  • 1
  • 9
  • At least related: http://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript – T.J. Crowder Nov 27 '16 at 10:55

1 Answers1

0

If you do not need this in multiple locations and want to keep it simple:

var isButtonAvaiable = true;
let subscription = button.addListener(function(){
    if(isButtonAvaiable === false) return;
    isButtonAvaiable = false;
    setTimeout(function() { isButtonAvaiable = true; }, /*disableButtonTimeInMs*/ 1000);

    let date = new Date();
    console.log(date.toTimeString() + ": button pressed!");
});
NtFreX
  • 10,379
  • 2
  • 43
  • 63