1

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.

Community
  • 1
  • 1
g5wx
  • 700
  • 1
  • 10
  • 30

3 Answers3

4

Make 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

putvande
  • 15,068
  • 3
  • 34
  • 50
3

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

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

Cracker0dks
  • 2,422
  • 1
  • 24
  • 39
  • Thanks for your answer. Is there any advantage with this method over another ones? – g5wx Jan 23 '14 at 15:35
  • I don't know if it is faster if you check every second... or generate your timer every click. – Cracker0dks Jan 23 '14 at 15:43
  • So your code should be more efficient/optimized? Sorry for asking, i don't know much about javascript/jquery. – g5wx Jan 23 '14 at 16:01
  • 1
    I don't know it... its just an other way to do it. You get a little timeshift between those solutions thats all i know :) – Cracker0dks Jan 23 '14 at 16:30