You have some possibilities:
1. If you wanna throw and error it's advised to use try...catch to handle the error, also this way the action the user's done will be executed when the condition is matched (when the block is finished animating) if you use finally. try...catch...finally DEMO
$(function(){
// cache dom
var $button = $('#button');
var $block = $('#block');
// event handlers
$button.on('click', moveBlock);
// functions
function checkAnimationState(){
if(!$block.hasClass('animating')){
$block.addClass('animating');
} else {
throw Error('Block is already animating... BE PATIENT.');
}
}
function moveBlock(){
try{
checkAnimationState(); // check for animation - essentially validation
}
catch(e){
console.log(e);
return false;
}
finally{
$block.animate(
{marginLeft:'400px'},
{
duration: 3000,
easing: "linear",
complete: function(){
$block.removeAttr('style').removeClass('animating');
}
}
)
}
}
});
2. You can use callback inside your checkAnimationState() function to execute or pass the animation command: callback DEMO
$(function(){
// cache dom
var $button = $('#button');
var $block = $('#block');
// event handlers
$button.on('click', moveBlock);
// functions
function checkAnimationState(callback){
if(!$block.hasClass('animating')){
$block.addClass('animating');
callback();
}
}
function moveBlock(){
checkAnimationState(function(){
$block.animate(
{marginLeft:'400px'},
{
duration: 3000,
easing: "linear",
complete: function(){
$block.removeAttr('style').removeClass('animating');
}
}
)
}); // check for animation - essentially validation
}
});
3. You can have your checkAnimationState() function return a value wether the condition is matched or not and use an if(...) statement. (I know this one is probably not what the OP wants, but I just wanted to mention it for other people who may stumble upon this question) if (...) DEMO
$(function(){
// cache dom
var $button = $('#button');
var $block = $('#block');
// event handlers
$button.on('click', moveBlock);
// functions
function checkAnimationState(){
var isAnimating = !$block.hasClass('animating');
$block.addClass('animating'); //since jQuery wont add an existing class, no need to check for it's existance before adding
return isAnimating;
}
function moveBlock(){
if(checkAnimationState()){ // check for animation - essentially validation
$block.animate(
{marginLeft:'400px'},
{
duration: 3000,
easing: "linear",
complete: function(){
$block.removeAttr('style').removeClass('animating');
}
}
)
}
}
});
!isAnimationRunning() && $block.animate(...Noif. \$\endgroup\$