JQuery: stop and start "setInterval"

I have a slide show on my site, but there is a problem with.

Here is my JS:

var size_ini = 1;
$(document).ready(function() {
    setInterval('$("#next").click()',10000)
    $("#next").click(function() {
        if(size_ini < 3);
        size_ini++;
        else
        size_ini = 1
        $(".sample").hide();
        $("#id" + size_ini).show();
        $(".comment" + size_ini).show();
        $(".comment_description" + size_ini).show();
    });
    $("#prev").click(function() {
        if(size_ini > 1)
        size_ini--;
        else
        size_ini = 3;
        $(".sample").hide();
        $("#id" + size_ini).show();
        $(".comment" + size_ini).show();
        $(".comment_description" + size_ini).show();
    });
});

As you can see, I have a timer lasting 10 seconds. for slides. I have the previous and next button. Therefore, when I pressed one of the buttons, the timer should stop and start again. I tried "clearInterval", but this does not work.

Can anyone tell how this works.

Here is the FIDDLE .

+3
source share
3 answers

var size_ini = 1;
$(document).ready(function () {
    var timer = setInterval('$("#next").click()', 10000); //assign timer to a variable
    $("#next").click(function () {
        if (size_ini < 3) size_ini++;
        else size_ini = 1
        $(".sample").hide();
        $("#id" + size_ini).show();
        clearInterval(timer); //clear interval
        timer = setInterval('$("#next").click()', 10000); //start it again
    });
    $("#prev").click(function () {
        if (size_ini > 1) size_ini--;
        else size_ini = 3;
        $(".sample").hide();
        $("#id" + size_ini).show();
        clearInterval(timer); //clear interval
        timer = setInterval('$("#next").click()', 10000); //start it again
    });
});
+9
source

If you want to clear the interval that you need to assign to a variable, then you can easily clear it -

var myInterval = setInterval('$("#next").click()',10000);

Then clear this:

clearInterval(myInterval);

, , reset , .

+3
<button id="start">Start</button>
<button id="stop">Stop</button>

var timer;
$("#start").click(function() {
    timer = setInterval(function(){$("#next").trigger("click");},"500");
});
$("#stop").click(function() {
    clearInterval(timer);
});
0

All Articles