Reputation: 162
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() {
//...
}
Upvotes: 0
Views: 2218
Reputation: 353
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);
Upvotes: 1