0

i have a problem, i need to make a interval of five second when you can execute a function or not. Why? Because i has listening a Arduino serial port, so the arduino serial port returns a lot of signals when i press a button, but in my node code, i want to handle just one signal every five seconds, and execute the sound() function, how i can made that?

serialport.on("open", function() {
  console.log("Serial Port Opend");
  serialport.on("data", function(data) {
    var start = Date.now();
    if (data[0]) {
      sound();
    }
  });
});

function sound() {
  //...
}
Santiago D'Antuoni
  • 164
  • 1
  • 2
  • 13
  • https://www.npmjs.com/package/lodash.throttle – Kevin Boucher May 16 '18 at 22:47
  • There is an excellent method of a sleep function (I'm assuming that's what you're looking for) https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep – Andrew May 16 '18 at 22:49

1 Answers1

1

Try a throttle function such as the one in lodash

https://lodash.com/docs/4.17.4#throttle

var _ = require('lodash');

serialport.on("open", function() {
  console.log("Serial Port Opend");
  serialport.on("data", function(data) {
    var start = Date.now();
    if (data[0]) {
      sound();
    }
  });
});

var sound = _.throttle(function () {
  //...
}, 5000);
  • Hi, thanks for you reply! That works but he is letting out a second request. I see two executions of `sound()`, first the function called one time and when the five seconds are elapsed, the function `sound` is executed again – Santiago D'Antuoni May 17 '18 at 13:18
  • That is expected. The first time you see data on the serial port it will call sound. It then gets more data (say for the next second) but won't call the sound() function for another 5 seconds. What I can suggest is removing your function after the serial data has finished? – Tarwin Stroh-Spijer May 18 '18 at 16:46