Reputation: 10219
Here is my code. It works "good". But if it loops for sometime, the page crashes. Also I cannot think of a way how to stop looping it when a button is clicked. Any ideas?
Cannot give a jsfiddle demo, because it crashes.
JavaScript:
$(document).ready(function () {
var stop = false;
function ivSlider($element, $continue) {
var current = $element.find('.current');
var next = current.next();
if (next.length == 0) next = $element.find(">:first-child");
setInterval(function () {
current.removeClass('current');
next.addClass('current');
if ($continue === true) ivSlider($element, true);
}, 4000);
}
ivSlider($('.slider'), true);
});
CSS:
.slider li {
display: none;
float: left;
padding-right: 10px;
}
.current {
display: block!important;
}
HTML:
<ul class="slider">
<li class="current">Slide 1</li>
<li>Slide 2</li>
</ul>
Upvotes: 2
Views: 687
Reputation: 56501
You can use clearInterval to stop it. Here I Would like to quote @T.J. Crowder's answer,
setInterval
sets up a recurring timer. It returns a handle that you can pass intoclearInterval
to stop it from firing.
you can try like this
1) stay with the boolean value stop
.
2) Have a separate method for animation.
function animation() {
current.removeClass('current');
next.addClass('current');
if ($continue === true) ivSlider($element, true);
}
3) Enclose with a separate function with a parameter and set a variable for setInterval
.
function yourFunc(stop) {
if (stop) {
interval = setInterval(animation, 4000);
}
else {
clearInterval(interval); // STOP the animation loop
}
}
4) On button click, pass the false
as parameter to stop animation.
$('button').click(function () {
yourFunc(false);
}
Update from your comments:
$(document).ready(function () {
function animation() {
var current = $('.slider').find('.current');
var next = current.next();
if (next.length == 0) next = $('.slider').find(">:first-child");
current.removeClass('current');
next.addClass('current');
ivSlider($('.slider'), true);
}
function yourFunc(stop) {
if (stop) {
interval = setInterval(animation, 1000);
} else {
alert('Im going to be stopped')
clearInterval(interval); // STOP the animation loop
}
}
$('button').on('click', function () {
yourFunc(false);
});
yourFunc(true);
});
Check out this JSFiddle
Upvotes: 1
Reputation: 3759
Change setInterval
to setTimeout
. As it is now, you have a fork bomb.
As for stopping the loop, you never set $continue
to false
.
$(document).ready(function () {
var stop = false;
var timeout = null;
function ivSlider($element, $continue) {
var current = $element.find('.current');
var next = current.next();
if (next.length == 0) {
next = $element.find(">:first-child");
}
timeout = setTimeout(function () {
current.removeClass('current');
next.addClass('current');
if ($continue === true) {
ivSlider($element, true);
}
}, 4000);
}
ivSlider($('.slider'), true);
$('.stop-button').click(function () {
if (timeout) {
clearTimeout(timeout);
}
});
});
Upvotes: 2