jQuery: Stop and start "setInterval"
30,719
Solution 1
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
});
});
Solution 2
If you're going to want to clear the interval you need to assign it to a variable, then you can clear it easily -
var myInterval = setInterval('$("#next").click()',10000);
Then clear like this -
clearInterval(myInterval);
Once the interval has been cleared make sure to reset it and assign it to a variable again if you want it to continue.
Solution 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);
});
Author by
Admin
Updated on July 19, 2022Comments
-
Admin almost 2 years
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.
-
Jay Blanchard over 10 yearsHis edits now should work - he has correctly reassigned the interval to a variable.
-
Tushar Gupta - curioustushar over 10 years@DOCTYPEHTML in a hurry i forgot to re-assign
setInterval
totimer
-
Admin over 10 yearsthank you, that have saved me a lot of time because of this problem
-
Tushar Gupta - curioustushar over 10 years@DOCTYPEHTML Welcome Happy to help :)
-
Admin over 10 yearsjsfiddle.net/dwayz here doesn't work this. In my script i used this doesn't work.
-
Tushar Gupta - curioustushar over 10 years@DOCTYPEHTML you are missing
var timer
just below DOM ready -->it should bevar timer = setInterval('$("#next").click()', 10000);
demo--> jsfiddle.net/cse_tushar/dwayz/1