I have a button which triggers the function inside set interval every 1 sec.
The value of the button changes to stop. When I hit stop I call the clearinterval method.
For some reason the clear interval method is not working.
This is my input
<input id="trigger" type="button" value="start"/>
my js function
$(function() {
$('#trigger').click(function() {
var timerId = 0;
var trigger = $('#trigger').val();
if(trigger == 'start') {
timerId = setInterval(function() {
$('#trigger').val('stop');
main();
}, 1000);
} else if(trigger == 'stop') {
clearInterval(timerId);
$('#trigger').val('start');
}
});
});
You have timerId is defined to be local to the scope of click(), so when you run it the second time (in the stop event) it will be 0 again. Try this