clearInterval 的问题
issues with clearInterval
我似乎无法让 clearInterval 以我认为应该的方式工作。我已经经历了很多其他的例子和问题。在每种情况下,我似乎都在做其他人正在做的事情,除了使用 onkeypress。我也尝试过其他各种按键选项,但没有成功。而且我还多次翻转代码,但无济于事。
下面是我一直在使用的基本代码片段,从较大的项目中简化了很多。您可能已经看出来了,我希望它一直打印 "poop " 直到按键停止它。如果我在它第一次打印 "poop" 之前按下一个按钮,它将停止并打印 "stopped pooping." 如果我等到它打印了一次 "poop" 之后,我无法让它停止按键。
请原谅它的粪便性质。
function pooping() {
document.write("poop ");
}
var pooper = setInterval(pooping, 1000);
document.onkeypress = function() {
clearInterval(pooper);
pooper = 0;
document.write("stopped pooping");
}
相同的代码,没有 document.write()
工作正常:
'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>
我似乎无法让 clearInterval 以我认为应该的方式工作。我已经经历了很多其他的例子和问题。在每种情况下,我似乎都在做其他人正在做的事情,除了使用 onkeypress。我也尝试过其他各种按键选项,但没有成功。而且我还多次翻转代码,但无济于事。
下面是我一直在使用的基本代码片段,从较大的项目中简化了很多。您可能已经看出来了,我希望它一直打印 "poop " 直到按键停止它。如果我在它第一次打印 "poop" 之前按下一个按钮,它将停止并打印 "stopped pooping." 如果我等到它打印了一次 "poop" 之后,我无法让它停止按键。
请原谅它的粪便性质。
function pooping() {
document.write("poop ");
}
var pooper = setInterval(pooping, 1000);
document.onkeypress = function() {
clearInterval(pooper);
pooper = 0;
document.write("stopped pooping");
}
相同的代码,没有 document.write()
工作正常:
'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>