Javascript clearInterval with button click

北慕城南 提交于 2019-12-12 13:07:01

问题


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);
});

Here's a js fiddle


回答1:


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

Working example:

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>



回答2:


First off, yes, when you assign a variable to a function, it self invokes.

Secondly, your click events are not working because you need assign the interval to the variable on the click, not invoke the function - there is no function to invoke, as you would see if you looked at your developer console.

Lastly, it is good practice to wrap the jQuery code in the document ready function to ensure all of your event handlers get bound properly.

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

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



回答3:


You're saving the wrong value. Try this:

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

var funkyId = setInterval(funky, 2000);

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


来源:https://stackoverflow.com/questions/36022067/javascript-clearinterval-with-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!