jQuery: Stop and start "setInterval"

user2628521 picture user2628521 · Feb 15, 2014 · Viewed 28.5k times · Source

I have a slideshow on my website but there is a problem with in.

Here, 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 of 10 sec. for slide. I have a previous and a next button. So when i clicked on one of the button the timer should stop and starts again. I have tried "clearInterval" but this doesn't work.

Can anyone tell how this works.

Here is FIDDLE.

Answer

Fiddle Demo

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
    });
});