Javascript clearInterval与按钮单击 [英] Javascript clearInterval with button click

查看:65
本文介绍了Javascript clearInterval与按钮单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将clearInterval绑定到按钮单击时,我遇到问题使其无法工作.而且,显然该函数是单独启动的...这是我的代码

I'm having issues getting clearInterval to work when I try to bind it to a button click. Also, apparently the function is starting on it's own... Here's my code

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

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

这是一个js小提琴

推荐答案

您忘记添加jquery库并且分配了错误的内容,它必须位于回调函数中.

You have forgot to add jquery library and have made wrong assignment, it needs to be inside callback function.

工作示例:

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>

这篇关于Javascript clearInterval与按钮单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆