Javascript clearInterval with button click

Viewed 7438

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

4 Answers

Here I am giving you the idea.

  1. declare a variable e.g. let x;
  2. create a function which you want to bind with setInterval. e.g. function funky() { alert("Hello World"); }
  3. assign start.onclick to a function which will assign the setInterval to x. e.g 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. assign stop.onclick to clearInterval(x) to stop the interval. e.g. stop.onclick = function() { clearInterval(x); // to stop the interval };

That's it. Easy right.

Related