1

Let me explain what I am trying to do:

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

So I making socket connection, and receive data like twice in a second. But i want to execute saveToDB function only once in a minute. How can i achieve that? Thanks!

Anna
  • 2,911
  • 6
  • 29
  • 42

2 Answers2

1

You would need to use something called debouncing function where a function would not be executed more than once in a given time frame.

Here is a link to an implementation in JS.

Here is a link to the lodash debounce.

Akrion
  • 18,117
  • 1
  • 34
  • 54
1

Using a simple variable to store the last SaveToDB time would help.

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;
   }
});
Ketan Yekale
  • 2,108
  • 3
  • 26
  • 33