单击按钮的Javascript clearInterval

DjH*_*DjH 3 javascript jquery clearinterval

当我尝试将其绑定到按钮单击时,我遇到了使clearInterval工作的问题.此外,显然该功能是从它自己开始...这是我的代码

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

$('#start').click(function() {
    funky();
});
$('#stop').click(function() {
    clearInterval(funky);
});
Run Code Online (Sandbox Code Playgroud)

这是一个小提琴

isv*_*all 6

你忘了添加jquery库并做了错误的赋值,它需要在回调函数内部.

工作范例:

var funky;

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

$('#stop').click(function() {
    clearInterval(funky);
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)