javascript - 与clearInterval相关的问题

标签 javascript setinterval clearinterval

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

下面是我一直在使用的基本代码片段,从较大的项目中进行了简化。正如您可能能够看出的那样,我希望它继续打印“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>

关于javascript - 与clearInterval相关的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33643497/

相关文章:

javascript - 仅在第一次加载 js 文件-在 angularjs : Making the ckeditor visible for first time only 中

javascript - 如何清除一个IFRAME的内容?

php - 如果输入为空并且输入不是现有的 Twitter 帐户,如何停止我的 javascript 运行?

javascript - 删除 setTimeout 间隔

javascript - 使用 setInterval 的多个实例

javascript - JS clearInterval 还是 window.clearInterval?

javascript - Node.js 中通过正则表达式分割数组

javascript - setInterval 用于运行带有 if 语句的函数不起作用

javascript - clearInterval 未清除 setInterval

javascript - 使用 javascript setInterval 函数,一个 div 启动内容到 fadeToggle,另一个 div 停止 fadeToggle 动画