Reputation: 333
I cannot seem to get clearInterval to work in the manner that I believe it should. I have been going through so many other examples and questions. In each case I seem to be doing what everyone else is doing, excepting the use of onkeypress. I have also tried various other keypress options with no luck. And I have also flipped around the code a bunch of different times to no avail.
Below is the basic pieces of code I have been working with, much simplified from the larger project. As you might be able to discern, I want it to keep printing "poop " until a keypress stops it. If I hit a button before it prints "poop" the first time, it will stop and print "stopped pooping." If I wait until after it has printed "poop" once, I cannot get it to stop with a keypress.
Please excuse the scatological nature of it.
function pooping() {
document.write("poop ");
}
var pooper = setInterval(pooping, 1000);
document.onkeypress = function() {
clearInterval(pooper);
pooper = 0;
document.write("stopped pooping");
}
Upvotes: 0
Views: 99
Reputation: 174957
Same code, without the document.write()
works fine:
'use strict';
let target = document.getElementById('target');
function pooping() {
// Normally would use console.log() here, but wanted the result visible
// in the snippet.
target.textContent += "poop ";
}
var pooper = setInterval(pooping, 1000);
document.onkeypress = function() {
clearInterval(pooper);
pooper = 0;
target.textContent += "stopped pooping";
}
<div id="target"></div>
Upvotes: 2