Reputation: 321
I have a return statement, and my condition is definitely being met. Yet the function still runs, not sure why.
<script>
var loop = true;
fade();
// rotate navigation banners
function fade(){
var divs = jQuery('.site-wide-notification');
var current = jQuery('.first-notification');
var currentIndex = divs.index(current),
nextIndex = currentIndex + 1;
if (nextIndex >= divs.length){
nextIndex = 0;
}
var next = divs.eq(nextIndex);
next.stop().fadeIn(2000, function(){
jQuery(this).addClass('first-notification');
setTimeout(fade, 3000);
});
current.stop().fadeOut(2000, function(){
jQuery(this).removeClass('first-notification');
});
jQuery('.site-wide-notification').click(function(){
console.log('Closed');
jQuery('.site-wide-notification').css('display', 'none');
loop = false;
});
if (!loop){
console.log('stop da loop');
return false;
}
}
This code is meant to rotate some banners at the top, fading them in and out, and when the user clicks on any of them it will set them all to display: none
. When the user clicks on any of them the console.log('Closed')
appears and loop is set to false
, then the if !loop
statement is entered and the console prints stop da loop, but the fade function continues running despite its return.
Upvotes: 0
Views: 71
Reputation: 5181
It doesn't matter whether your function returns false
(in the !loop
case) or undefined
(otherwise). When you call fade()
, it sets up a timer to call fade()
again. Unconditionally.
Move your if (!loop) return;
test to the top of the function. That way, if the loop isn't supposed to continue, the function bails out before setting up the next iteration.
Upvotes: 1