Javascript clearInterval with button click

Javascript clearInterval with button click

当我尝试将 clearInterval 绑定到按钮单击时,我无法正常工作。另外,显然该功能是自行启动的...这是我的代码

var funky = setInterval(function() {
    alert('hello world');
}, 2000);

$('#start').click(function() {
    funky();
});
$('#stop').click(function() {
    clearInterval(funky);
});

Here's a js fiddle

您保存的值有误。试试这个:

var funky = function() {
    alert('hello world');
}

var funkyId = setInterval(funky, 2000);

$('#start').click(function() {
    funky();
});
$('#stop').click(function() {
    clearInterval(funkyId);
});

首先,是的,当您将变量分配给函数时,它会自行调用。

其次,您的点击事件不起作用,因为您需要将时间间隔分配给点击时的变量,而不是调用该函数 - 没有可调用的函数,正如您查看开发人员控制台时所看到的那样。

最后,最好将 jQuery 代码包装在文档就绪函数中,以确保正确绑定所有事件处理程序。

$(function () {
  var funky;
  $('#start').click(function() {
    funky = setInterval(function() {
      alert('hello world');
    }, 1000);
  });

  $('#stop').click(function() {
      clearInterval(funky);
  });
});

您忘记添加jquery库并且赋值错误,需要在回调函数中。

工作示例:

var funky;

$('#start').click(function() {
  funky = setInterval(function() {
    alert('hello world');
  }, 2000);
});

$('#stop').click(function() {
    clearInterval(funky);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">start</button>
<button id="stop">stop</button>

这里给大家介绍一下。

  1. 声明一个变量,例如let x;
  2. 创建一个要与 setInterval 绑定的函数。 例如 function funky() { alert("Hello World"); }
  3. start.onclick 分配给一个函数,该函数会将 setInterval 分配给 x。 例如 start.onclick = function(){ clearInterval(x); // to prevent multiple interval if you click more than one x = setInterval(funky, 2000); // assign the setInterval to x };
  4. stop.onclick分配给clearInterval(x)以停止间隔。 例如stop.onclick = function() { clearInterval(x); // to stop the interval };

就是这样。简单吧。