I'm trying to setup a function in JavaScript to fade in or fade out some elements on my page. The fade themselves work fine, but my problem occurs when one of them tries to cancel the actions of the other one.
//I know this is ugly, I'm just learning JavaScript again and plan to recode it after I learn some more...
var fadeOut = false
//set out to true to fade out, false to fade in
function fade(out) {
var steps = 1
var outSpeed = 100
var inSpeed = 10
var timer = 0
if (out) {
//fade out
fadeOut = true
for ( var i=100; i>=0; i-=steps ) {
if ( fadeOut ) {
setTimeout("set_el_opacity(" + (i / 100) + ")",
timer+=steps
} else {
break;
}
}
} else {
//fade in
fadeOut = false
for ( var i=0; i<=100; i+=steps ) {
if( !fadeOut ) {
setTimeout("set_el_opacity(" + (i / 100) + ")",
timer+=steps
} else {
break;
}
}
}
}
Now, the fade out is set to run slower than the fade in. I want the user to see it fade out slowly so they know it's on purpose, and then fade back in quickly if the elements are needed (removing some clutter from the screen when it's not needed).
fade(true) works fine, fade(false) works fine and is faster. My problem occurs when I call fade(true) followed shortly by fade(false). The fades fight with each other and then, since the fade(true) call runs faster it finishes first and the fade(false) call proceeds to fade it all out fully.
My question is: what can I do to make the fade(false) call cancel the loop of the fade(true) call?