i've got a simple setInterval
function for radio buttons to loop on load.
I would like to add a button, which could start or stop the loop. I've added click function for the function, but don't know how to stop it afterwards.
Here is what i've got so far: jsfiddle
Also, if i click the button more times in a row, loop goes berserker - any help appricieted :)
p.s. I've also checked:
start & stop / pause setInterval with javascript, jQuery and
Javascript loop-problem with setTimeout/setInterval
but i was wondering in the dark on how to use those answers as i'm javascript noob.
i've got a simple setInterval
function for radio buttons to loop on load.
I would like to add a button, which could start or stop the loop. I've added click function for the function, but don't know how to stop it afterwards.
Here is what i've got so far: jsfiddle
Also, if i click the button more times in a row, loop goes berserker - any help appricieted :)
p.s. I've also checked:
start & stop / pause setInterval with javascript, jQuery and
Javascript loop-problem with setTimeout/setInterval
but i was wondering in the dark on how to use those answers as i'm javascript noob.
3 Answers
Reset to default 4Make a reference to your setInterval
so you can use clearInterval(yourreference)
.
To start / stop, you can add an extra boolean variable to toggle start and stop.
var t;
var running = false;
$("#start-stop").click(function(){
clearInterval(t);
running = !running;
if (!running)
return;
t = setInterval(function(){
$('.wrap input')
.eq( ( $('input:checked').index() + 1 ) % 3 )
.prop('checked',true);
},1000);
});
Fiddle
Try
jQuery(function () {
var timer;
$("#start-stop").click(function () {
if (timer) {
clearInterval(timer);
timer = undefined;
} else {
timer = setInterval(function () {
$('.wrap input')
.eq(($('input:checked').index() + 1) % 3)
.prop('checked', true);
}, 1000);
}
});
})
Demo: Fiddle
le solution without clearInterval
jQuery(function () {
var toggle = null;
$("#start-stop").click(function () {
if(toggle == null) {
toggle = false;
setInterval(function () {
if(toggle)
$('.wrap input').eq(($('input:checked').index() + 1) % 3).prop('checked', true);
}, 1000);
}
toggle = !toggle;
});
});
Fiddle HERE