I am trying to make disappear loop using javascript, the codes running well.. but i want to make the loop stop after several times.. this is the codes :
$(document).ready(function() {
var j = 0;
var delay = 9000; //millisecond delay between cycles
function cycleThru(){
var jmax = $("ul#cyclelist li").length -1;
$("ul#cyclelist li:eq(" j ")")
.animate({"opacity" : "1"} ,400)
.animate({"opacity" : "1"}, delay)
.animate({"opacity" : "0"}, 400, function(){
(j == jmax) ? j=0 : j ;
cycleThru();
});
};
cycleThru();
});
What should i do if i want to stop the loop after 10x?
Thanks for the help
CodePudding user response:
An easy way to solve this would be to accept a cycles
parameter in cycleThru
, which is used to specify the amount of cycles after which recursion is stopped.
function cycleThru(cycles = Infinity) {
You then add a guard clause to the recursive function to stop the recursion.
if (cycles <= 0) return;
When you recursively call cycleThru
reduce the cycles
by one.
cycleThru(cycles - 1);
Finally pass the amount of cycles with the initial cycleThru
call.
cycleThru(10);
Resulting in the following code:
$(document).ready(function () {
var j = 0;
var delay = 9000; // millisecond delay between cycles
function cycleThru(cycles = Infinity) {
if (cycles <= 0) return;
var jmax = $("ul#cyclelist li").length - 1;
$("ul#cyclelist li:eq(" j ")")
.animate({"opacity" : "1"} ,400)
.animate({"opacity" : "1"}, delay)
.animate({"opacity" : "0"}, 400, function () {
(j == jmax) ? j=0 : j ; // or: j = (j 1) % jmax
cycleThru(cycles - 1);
});
};
cycleThru(10);
});
CodePudding user response:
Take this line var jmax = $("ul#cyclelist li").length -1;
outside the function. Else every time cycleThru
is called it will create new j
$(document).ready(function() {
var jmax = $("ul#cyclelist li").length - 1;
var j = 0;
var delay = 9000; //millisecond delay between cycles
function cycleThru() {
$("ul#cyclelist li:eq(" j ")")
.animate({
"opacity": "1"
}, 400)
.animate({
"opacity": "1"
}, delay)
.animate({
"opacity": "0"
}, 400, function() {
if (j !== max) {
j ;
cycleThru();
}
});
};
cycleThru();
});