最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Startstop function with setInterval - Stack Overflow

programmeradmin7浏览0评论

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.

Share Improve this question edited May 23, 2017 at 12:28 CommunityBot 11 silver badge asked Jan 23, 2014 at 15:17 g5wxg5wx 7201 gold badge10 silver badges31 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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

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

发布评论

评论列表(0)

  1. 暂无评论