Regarding these two functions, which do the same thing...
Large and confusing:
var fade = function(flag){ if (volumeIntervalId) clearInterval(volumeIntervalId); switch (flag){ case 'in': volumeIntervalId = setInterval(function(){ var vol = songInstance.getVolume(); if (vol < 1){ songInstance.setVolume( vol + volumeIncrement ); }else{ clearInterval(volumeIntervalId); } }, volumeIntervalDelay); break; case 'out': volumeIntervalId = setInterval(function(){ var vol = songInstance.getVolume(); if (vol > 0){ songInstance.setVolume( vol - volumeIncrement ); }else{ clearInterval(volumeIntervalId); songInstance.stop(); } }, volumeIntervalDelay); break; default: clearInterval(volumeIntervalId); break; } },
Slighty smaller but maybe more confusing:
var fade = function(flag){ if (volumeIntervalId) clearInterval(volumeIntervalId); volumeIntervalId = setInterval(function(){ var vol = songInstance.getVolume(); if (flag === 'in'){ if (vol < 1) { songInstance.setVolume( vol + volumeIncrement ); return; } } else if (flag === 'out'){ if (vol > 0) { songInstance.setVolume( vol - volumeIncrement ); return; }else{ songInstance.stop(); } } clearInterval(volumeIntervalId); }, volumeIntervalDelay); },
How could I make that simpler/cleaner/easier to read? Maybe split into more functions?
It's interesting how the 2nd function's setInterval
anonymous function keeps the value of 'flag' due to the closure. Is there any risk? Should I avoid that?
Maybe (the obvious) use two functions (fadeIn
and fadeOut
)? Why do people (like me) tend to complicate things like that?
Update
I guess this is better:
fadeIn: function(){
if (volumeIntervalId) clearInterval(volumeIntervalId);
volumeIntervalId = setInterval(function(){
var vol = songInstance.getVolume();
if (vol < 1){
songInstance.setVolume( vol + volumeIncrement );
}else{
clearInterval(volumeIntervalId);
}
}, volumeIntervalDelay);
},
fadeOutAndStop: function(){
if (volumeIntervalId) clearInterval(volumeIntervalId);
volumeIntervalId = setInterval(function(){
var vol = songInstance.getVolume();
if (vol > 0){
songInstance.setVolume( vol - volumeIncrement );
}else{
songInstance.stop();
clearInterval(volumeIntervalId);
}
}, volumeIntervalDelay);
},