2014-10-09 124 views
-2

我想知道有沒有辦法在jQuery中停止代碼執行,直到返回函數結果。在jQuery中暫停代碼執行

functionName() { 
    //user inserts something 
    return user_insertion; 
} 
$(document).ready(function() { 
    //code before 
    if (var1.length > 1) result = functionName(data); 
    else result = [data: 1, data: 2, data: 3]; 
    //code after, the one I want to pause execution of 
    //do something with result that user inserted 
}); 
+0

*「我想知道有沒有辦法在jQuery的停止代碼執行,直到返回函數的結果。」 * **電話** – 2014-10-09 14:35:38

+0

如果你。閱讀其他問題,他們都應該說你不應該這樣做。 – Barmar 2014-10-09 14:36:13

+1

歡迎使用異步編程。 – Andy 2014-10-09 14:37:51

回答

0

我們根本在JavaScript中沒有sleep功能,因爲它不支持線程(除了WebWorkers的概念,但是這是超出範圍)。

你正在尋找的可能是承諾模式。看看這裏的文檔: http://api.jquery.com/promise/

你應該有你的functionName()履行預先定義的承諾。

0

也許這可以幫助你:

functionName() { 
    //user inserts something 
    return user_insertion; 
    callback(); 
} 
function callback(){ 
    // do something after; 
} 
$(document).ready(function() { 
    //code before 
    if (var1.length > 1) result = functionName(data); 
    else result = [data: 1, data: 2, data: 3]; 
    //code after, the one I want to pause execution of 
    //do something with result that user inserted 
}); 
+0

您的回報和執行回調失靈。 – 2014-10-09 14:42:20