Reputation: 592
Is there a way I can tell the browser to wait to start on function until after another is completed?
For example, in the following for loop, I'd like for contact() to fire and conclude, prior to moveForward() commencing.
for ($i = 0; $i <= ($slugPace - 1); $i++ ) {
contract();
moveForward();
reset();
};
I attempted using $.when(// your first function).then(// your second function);
mentioned in this stackoverflow thread, but the JS functions in the three listed functions continued to fire simultaneously.
Here is the code in total, if that helps:
//Contracting the slug once:
function contract(){
$("#slug").animate({
marginTop: 0,
width: $slugThinner,
height: $slugHigher,
}, 250);
$(".slugContainer").animate({
marginLeft: $slugLeftMargin,
}, 250);
};
//Extending the slug out and move him forward once:
function moveForward(){
$slugLeftMargin += $slugStepsLength;
$("#slug").animate({
marginTop: $slugMarginJS,
width: $slugWide,
height: $slugHigh,
}, 250);
$(".slugContainer").animate({
marginLeft: $slugLeftMargin,
}, 250);
};
function movement(){
for ($i = 0; $i <= $slugStepsTotal; $i++ ) {
contract();
moveForward();
};
}
function reset(){
if ($slugLeftMargin > $screenWidth) {
$slugLeftMargin = $slugWide * -1;
$("#slug").stop().hide;
$(".slugContainer").stop.css('margin-left',$slugLeftMargin);
for ($i = 0; $i <= ($slugPace - 1); $i++ ) {
contract();
moveForward();
};
}
}
//Looping the contractions to move our little friend across the screen:
$("#slug").click(function(){
//alert('Slug width: ' + $slugWide + ', Slug height: ' + $slugHigh + ', Screen width: ' + $screenWidth + ', Slug steps total: ' + $slugStepsTotal + ', Slug higher: ' + $slugHigher + ', Slug thinner: ' + $slugThinner);
//alert($slugStepsTotal);
//alert('One step: ' + $slugStepsLength + '; Total steps: ' + $slugStepsTotal + '; Screen width: ' + $screenWidth);
$("#slug").show();
$(".clickMe").fadeOut(300);
$.when(movement).then(reset());
});
Thank you in advance for your help.
Upvotes: 1
Views: 89
Reputation: 8700
In general terms, since you're using the animate
method, you could do something with callbacks, say:
function contract(callback) {
$("#slug").animate({
marginTop: 0,
width: $slugThinner,
height: $slugHigher,
}, 250);
$(".slugContainer").animate({
marginLeft: $slugLeftMargin,
}, 250, function() {
callback();
}
);
And you'd call contract like this:
contract(function(){ moveForward(); });
You can read-up a bit more about animate
here
That is the basic idea of what you need: callbacks.
Good luck mate!
Upvotes: 2