Cristian Cristian - 4 months ago 9
HTML Question

javascript wait til function is finished

I have a javascript function that goes like this:

$(document).keydown(function(e) {
switch(e.which) {
case 38:
moveUp();
break;
case 40:
moveDown();
break;
}
});
function moveDown() {
$('element').animate({top: "100%"}, {duration: 1000 });
}
function moveUp() {
$('element').animate({top: "-100%"}, {duration: 1000 });
}


My question is how would I create a delay in the
keydown
function that tells it that it has to wait until the function
moveUp()/movedown()
is finished before calling the function again without creating a queue?

Thank you for all the advise, by the way, I cant use
setTimeout
because it would cause a delay on every initial function.

Answer

This should help you, I used the complete function of the animate to execute the next action as soon as it's finish animating.

var isAnimating = false;
var callAfterFinish = undifined;
$(document).keydown(function(e) {
    switch(e.which) {
        case 38:
            moveUp();
            break;
        case 40:
            moveDown();
            break;
    }
});
function moveDown() {
    if(!isAnimating){
        $('element').animate({top: "100%"}, {duration: 1000 },function(){
            if(!callAfterFinish) {
                callAfterFinish();
                callAfterFinish = undifined;
            }
            isAnimating = false;
        });
        isAnimating = true;
    } else if(!callAfterFinish) {
        callAfterFinish = moveDown;
    }
}
function moveUp() {
    if(!isAnimating){
        $('element').animate({top: "-100%"}, {duration: 1000 },function(){
            if(!callAfterFinish) {
                callAfterFinish();
                callAfterFinish = undifined;
            }
            isAnimating = false;
        });
        isAnimating = true;
    } else if(!callAfterFinish) {
        callAfterFinish = moveUp;
    }
}