4

The function is not running after I include the function to pause the setinterval function using the space bar

if(event.keyCode == 32 ){
            clearInterval(timerId);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • 2
    Are you listening for keyboard inputs - please provide more context – Nick Parsons Jun 12 '19 at 05:26
  • 4
    please share more code – brk Jun 12 '19 at 05:26
  • 2
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [*How to create a Minimal, Reproducible Example*](https://stackoverflow.com/help/minimal-reproducible-example). – RobG Jun 12 '19 at 06:11
  • 1
    I think the answers in this question: https://stackoverflow.com/questions/21277900/javascript-pausing-setinterval are relevant to your problem – Israel Obanijesu Jun 12 '19 at 06:39

1 Answers1

5

All you are looking is to add an eventListner to the DOM,which can listen to key press events of keyboard

   
// adding eventListner to he document for keypress event
document.addEventListener("keypress", (event) => {

  if (event.keyCode == 32) {  // if the spacebar (keycode 32 is pressed)
    clearInterval(myVar);  // clear the interval
  }

})

// Setting the Intevral here
var myVar = setInterval(myTimer, 1000);
function myTimer() {
  var d = new Date();
  var t = d.toLocaleTimeString();
  document.getElementById("demo").innerHTML = t;
}
<div id="demo"></div>
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
  • 1
    Code–only answers aren't helpful. The OP doesn't know enough to even post an attempt so they can't really be expected to understand code with zero comments, documentation or explanation. Also, the code doesn't illustrate pausing, but stopping/cancelling it. – RobG Jun 12 '19 at 06:13