2011-10-24 71 views
1

如何停止執行功能,直到完成另一個功能?jQuery - 繼續之前執行功能

$('#div').load('sub.html', function() { 

    //Do this once done loading the sub.html file 
    setTimeout(function() { 

     //Run SomeFunction(); before doing anyhing else 
     $('#tabsWrapper').removeClass('ajaxLoading'); 
     $('#tabsWrapper #loaderDiv').fadeIn(500); 

    } , 1000); 

}); 

我要確保SomeFunction()$('#tabsWrapper').removeClass('ajaxLoading');等做過..

任何建議,我怎麼能做到這一點?任何幫助非常感謝。

+0

返回值,看看它是否做了,你能不能返回一個循環,直到值。 – Dev

+0

在.load上使用回調。 http://stackoverflow.com/questions/6688958/jquery-load-callback-scrolling-css-overflow,我相信會工作。 – Matt

+1

似乎是相當正常的腳本流程。 simeFunction沒有像'ajax'那樣的東西,它會以你需要的方式運行 – Varun

回答

1

返回從SomeFunction()一定的價值,並把狀況是這樣的:

var result = null; // important to put it here eg before setTimeout 

//Do this once done loading the sub.html file 
setTimeout(function() { 

    result = SomeFunction(); 

    if (result === 'whatever that function returns') { 
     $('#tabsWrapper').removeClass('ajaxLoading'); 
     $('#tabsWrapper #loaderDiv').fadeIn(500); 
    } 

} , 1000); 

更好的辦法是使用自調用匿名函數是這樣的:

(function foo(){ 
    doStuff; 

    setTimeout(foo, 500); 

})() 

Here setTimeout will only trigger when doStuff is finished.

+0

quastion是 - 如果'SomeFunction()'沒有在'if語句'之前完成,它會被跳過嗎?我想確保執行順序得到維護。 – Iladarsda

+0

@NewUser:看到後面的方法:) – Sarfraz

+0

幾乎在那裏。 「doStuff();'完成後,我可以在哪裏放置代碼? 'setTimeout'之前或之後,或者也許在裏面?但如何?:) – Iladarsda

2
$('#div').load('sub.html', function(response, status) { 

    if(status=="success"){ 
      //do your stuff here ..its loaded 
    } 

}); 
2

使用回調方法。

請參閱從SomeFunction JQuery的API

相關問題