让我解释一下我要做什么:
const ws = new WebSocket(url);
ws.on('message', function (data) {
//some code
savetoToDB(result) //this is my function, that i want to be called once in a minute
});
所以我建立了套接字连接,每秒接收两次数据。但是我只想在一分钟内执行一次saveToDB函数。我该如何实现?谢谢!
答案 0 :(得分:1)
您将需要使用名为debouncing function的东西,其中某个函数在给定的时间范围内最多执行一次。
这里是指向implementation in JS的链接。
这里是指向lodash debounce的链接。
答案 1 :(得分:1)
使用一个简单的变量来存储上次SaveToDB时间会有所帮助。
const ws = new WebSocket(url);
var savedAt = 0; //Initialization
ws.on('message', function (data) {
//some code
var currentTime = Date.now();
if(currentTime-savedAt>60000){//60000milliseconds
savetoToDB(result); //this is my function, that i want to be called once in a minute
savedAt = currentTime;
}
});