有沒有一種方法可以告訴瀏覽器等待啓動功能,直到另一個完成?如何在單個函數中調整JavaScript事件的順序?
例如,在下面的for循環中,我希望contact()在fireForward()開始之前觸發並結束。
for ($i = 0; $i <= ($slugPace - 1); $i++) {
contract();
moveForward();
reset();
};
我試圖使用this stackoverflow thread提到$.when(// your first function).then(// your second function);
,但在三家上市職能的JS功能繼續同時開火。
這裏是總的代碼,如果這能幫助:
//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());
});
預先感謝您的幫助。
我想你可以用Observer模式解決這個問題。 http://en.wikipedia.org/wiki/Observer_pattern – JSager 2012-03-26 21:33:35