Search code examples
javascriptnode.jswebsocketws

How to clear interval in WebSocket when some condition is met outside the scope?


I have a simple WebSocket server like this:

wss.on('connection', ws => {
  console.log('user is connected to the server')
  const t = setInterval(() => {
    ++count
    ws.send(count)
  }, 2000);
})

and I have a code down the page like

setInterval(() => {
  ++flag
}, 2000);

flag being let flag = 1. I'd like to clear the first interval when flag hits a certain number like 10. How do I achieve that?


Solution

  • You have to define t outside of your function to extend the scope

    let t;
    wss.on('connection', ws => {
      console.log('user is connected to the server')
      t = setInterval(() => {
        ++count
        ws.send(count)
      }, 2000);
    })
    

    and then clear it when flag is ok

    let flag = 1;
    setInterval(() => {
      ++flag;
      if(flag===10)
        clearInterval(t);
    }, 2000);
    

    And also, I advise you to use more expressing name than just t.

    Maybe, you also want to clear the second timer

    let flag = 1;
    let secondTimer = setInterval(() => {
      ++flag;
      if(flag===10) {
        clearInterval(t);
        clearInterval(secondTimer);
      }
    }, 2000);
    

    NB : not tested !