-1

I would like to, when x reaches 5, exit out of a document.onkeydown function. I tried this:

var x = 0

document.onkeydown = function() {
  console.log("Still running...")

  x += 1
  if (x >= 5) {
    break
  }
}

but the console says that it was an illegal break statement. I have also tried using a return statement to exit out of the onkeydown loop, but that hasn't worked either. Do any of you know how to exit out of one of these? If so, I would very much like to know it.

  • Possible duplicate of [JavaScript: remove event listener](http://stackoverflow.com/questions/4402287/javascript-remove-event-listener) – JJJ Apr 25 '17 at 17:47
  • `return false;`? It's a bit unclear what you mean by "exit out". Do you mean you want to cancel the event, try http://stackoverflow.com/q/3036243/215552 – Heretic Monkey Apr 25 '17 at 17:47
  • i mean... it'l exit right after the if statement anyway... exiting inside of it makes no difference. – Kevin B Apr 25 '17 at 21:50

1 Answers1

0

I don't see any problem other than replacing break to return... Your code comes out of funtion when X reaches 5

var x = 0

document.onkeydown = function() {
  console.log("Still running...")

  x += 1
console.log("x" + x)
  if (x >= 5) {
console.log("Existing..." )
    return;
  }
else{
/** Do your stuff **/
console.log('Working')}
}
Kumar Nitesh
  • 1,634
  • 15
  • 18