issues with clearInterval

issues with clearInterval

本文关键字:clearInterval with issues      更新时间:2023-09-26

我似乎无法让clearInterval以我认为应该的方式工作。我已经经历了很多其他的例子和问题。在每一种情况下,我似乎都在做其他人正在做的事情,除了使用onkeypress。我也尝试过其他各种按键选项,但没有成功。我也多次翻阅代码,但都无济于事。

以下是我一直在使用的基本代码,从更大的项目中简化了很多。正如你所能看到的,我希望它一直打印"便便",直到按键停止。如果我在它第一次打印"便便便"之前按下按钮,它就会停止并打印"停止便便"。如果我等到它打印了一次"便便"之后,我就无法用按键停止它。

请原谅它的粪便学性质。

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>