2

I have a question, I'd like to stop the setinterval function when I hit the space bar, this script doesnt work, what is the mistake? thanks

window.onload = function(){
  var button=document.getElementsByClassName('btn btn-primary')[0];
  setInterval(function(){ 
    button.click();
    if(event.keyCode == 32 ){
      return;
    }
  }, 1000);
}
ulissess
  • 23
  • 1
  • 4
  • 1
    you'll need to save the value returned by `setInterval` and use it in a `clearInterval` call - you'll also need an event listener to handle keyboard events – Jaromanda X May 20 '20 at 01:59
  • Does this answer your question? [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – ggorlen May 20 '20 at 01:59

3 Answers3

1

You just need to listen for keyup event, then check if the key was the spacebar, if so, you clear the interval using it's id.

window.onload = function() {
  var button = document.getElementsByClassName('btn btn-primary')[0];

  var intervalId = setInterval(function() { 
    button.click();
  }, 1000);

  document.body.onkeyup = function(e){
    if(e.keyCode == 32) clearInterval(intervalId)
  }

}
Ahmed Hammad
  • 2,798
  • 4
  • 18
  • 35
0

This is the answer:

window.onload = function(){
  var button=document.getElementsByClassName('btn,btn-primary')[0];
  let a=setInterval(frame, 1000);
  function frame(){ 
    button.click();
    if(event.keyCode == 32 ){
      clearInterval(a);
      return;
    }
  }
}
Mohamed Reda
  • 136
  • 1
  • 11
-2

I think something like this :

window.onload = function(){
  var button=document.getElementsByClassName('btn btn-primary')[0];
  var a = setInterval(function(){ 
    button.click();
    if(event.keyCode == 32 ){
      clearInterval(a);
    }
  }, 1000);
}
CozLex
  • 51
  • 4