简体   繁体   中英

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?

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM