仅在x秒内调用一次函数

时间:2016-11-27 10:53:20

标签: javascript node.js

我买了一个亚马逊短跑按钮,正在使用dash-button library。我有这段代码:

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!");
});

有时在按下按钮时会调用该函数两次。这是输出:

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

有没有办法为函数添加一种冷却时间,以便每隔x秒只能调用一次?

1 个答案:

答案 0 :(得分:0)

如果您不需要在多个位置使用它并希望保持简单:

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!");
});