WebSocket: Execute setInterval function for specific time period

socket.setTimeout(function () {

    socket.setInterval(function interval() {

      socket.send(jsonText);

      console.log('Message sent: ');

   }, 50);

    }, 45000);

The above code will start to send message after 45 seconds.
but I want to send messages for first 45 seconds rather than after 45 seconds.
Can any of you please help me with that?

Hello!

Not sure I fully understand what you’re looking to do. Are the calls just the wrong way around?

socket.setInterval(() => {
  // executed every 50ms
}, 50);

socket.setTimeout(() => {
  // executed after 45sec
  socket.send(jsonText);

  console.log('Message sent: ');
}, 45000);

If you need to stop sending messages every 50ms after 45sec, you would do something like this:

const interval = socket.setInterval(() => {
  // executed every 50ms
}, 50);

socket.setTimeout(() => {
  clearInterval(interval); // stops messages every 50ms

  socket.send(jsonText);

  console.log('Message sent: ');
}, 45000);