DjH
DjH

Reputation: 1498

Javascript clearInterval with button click

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

Upvotes: 3

Views: 9949

Answers (4)

Jamil Ahmed
Jamil Ahmed

Reputation: 21

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.

Upvotes: 0

isvforall
isvforall

Reputation: 8926

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>

Upvotes: 6

mhodges
mhodges

Reputation: 11116

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

Upvotes: 3

Amit
Amit

Reputation: 46323

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

Upvotes: 0

Related Questions