如何使 clearInterval 函数工作

How to make clearInterval function work

本文关键字:工作 函数 clearInterval 何使      更新时间:2023-09-26

我是一个极端的新手,所以对一个公认的愚蠢问题表示歉意。但是我已经研究并尝试了几种方法来使此功能工作,但似乎无法获得它。我正在上在线课程,我正在尝试构建一个简单的应用程序,其中图像在屏幕上移动,用户尝试单击它 - 当他们单击图像时,图像消失。我能够构造 setInterval 函数,但无法让 clearInterval 函数工作。

(为代码的政治性质道歉!只是一点美国的政治幽默。无意冒犯!

<h2>See if you can click on Hillary before she changes her position!</h2>
<p class="bold">This is your time:<span id="time">0</span>s</p>
<div id="box">
  <img src="images/hillary.jpg" style="width:100%; height:100%">    
</div>
<script type="text/javascript">

var time; var top; var left;
var makeBox; 
function makeBox() {
    time=Math.random();
    time=1000*time;
    setInterval(function () {
      top=Math.random();
      top=top*300;
      left=Math.random();
      left=left*1000;
      document.getElementById("box").style.top=top+"px";
      document.getElementById("box").style.left=left+"px";
      document.getElementById("box").style.display="block";
      createdTime=Date.now();
    },time);
}
makeBox();
function myStopFunction() {
  clearInterval(makeBox);
}
document.getElementById("box").onclick= function(){
  clearInterval(makeBox);
  this.style.display="none";

};
</script>

贾斯汀

为了清除计时器,您需要首先存储它。使用 setInterval 创建间隔时,应将其返回值存储在变量中。然后,当您调用 clearinterval 时,将变量传入。

以下代码片段包含您需要的内容:

var myTimer;
function makeBox() {
    time=Math.random();
    time=1000*time;
    myTimer = setInterval(function () {
      top=Math.random();
      top=top*300;
      left=Math.random();
      left=left*1000;
      document.getElementById("box").style.top=top+"px";
      document.getElementById("box").style.left=left+"px";
      document.getElementById("box").style.display="block";
      createdTime=Date.now();
    },time);
}
makeBox();
function myStopFunction() {
  clearInterval(myTimer);
}