1

Does anyone know how does this if statement "escape 2 functions at the same time"

client.on('message', message => {
   if (Math.floor(Math.random()*20) === 19) return;
   //rest of code
}

Like it escapes its if check and the .on message event. Also, this is probably a dupe, but I couldn't find what I was looking for or didn't know what to search for. Just to add, an analogy would be like when you use break; + labels: to stop a loop from going on. See, if I used a return; it would only stop the if statement (in the below code ofc), and the for loop would continue. But if I used a break start; it would also stop the for loop, this is what am trying to do.

start: {
  for (var i = 0; i > x; i++) {
    if (x === 1) {
      break start;
    }
    //code
  }
}
Robigan 06
  • 33
  • 4
  • The return is already done in Math.floor() and in Math.random() when you evaluate them. Assuming these are the two functions you are talking about. – Leon Apr 25 '20 at 19:36
  • @GUNNM No I mean like how do I escape the client.on message,like what if I want it to stop right there an then – Robigan 06 Apr 25 '20 at 20:19
  • I didn't get it was jquery. Surely "event.stopPropagation();" Take a look at this answer: https://stackoverflow.com/a/4379459/3520059 – Leon Apr 25 '20 at 20:35
  • @GUNNM this is discord.js, but thx anyways – Robigan 06 Apr 26 '20 at 13:42
  • @Robigan06 See answer below. Not sure what it is you're trying to do, perhaps you could elaborate a little more in your question. – Richard Dunn Apr 26 '20 at 13:55
  • 1
    @Robigan06 what do you mean by "escape 2 functions at the same time"? Please show a short but complete example that demonstrates the current way it works and better explain what you are trying to achieve, at the moment your question isn't clear. – James Apr 26 '20 at 13:55
  • @James what I mean is can I stop the client.on message function to continue? Like can I use something like break w/ labels to stop a piece of code from executing? – Robigan 06 Apr 26 '20 at 14:23

2 Answers2

0

You can't escape the if condition. If you want this to do nothing, then simply return.

client.on('message', message => { return; })

// or, more concisely

client.on('message', () => {})

But this is a strange thing to do, unless you were trying to override the on callback method. But I assume is an event emitter that can have multiple subscribers, so that doesn't make sense either.

Richard Dunn
  • 6,165
  • 1
  • 25
  • 36
0

I guess what you want do is to detach your listener from emitter on certain condition. You would have to change your calls a little: add a function name and you will be able to adress it its body. Then you just detach your listener when your condition is met:

client.addListener('message', function onMessage(message) {
   if (Math.floor(Math.random()*20) === 19) {
      client.removeListener('message', onMessage);
   }
}
dkuznietsov
  • 298
  • 1
  • 9