【问题标题】:How can I make jquery wait for one function to finish before executing another function?如何让 jquery 在执行另一个函数之前等待一个函数完成?
【发布时间】:2012-10-23 12:41:28
【问题描述】:
function test(){
var distance=null;
       first();
       second();
       third();
alert(distance);//it shows null always because it take 2 second to complete.

}
 function first(tolat, tolon, fromlat,fromlon){

// calulating road distance between two points on the map using any other distance caluculating apis. 

distance=dis;  // update the value of distance but it takes 2 second to complete.

}
 function second(){}
 function third(){}

我的代码中有这种情况,现在在第一次和第二次完成执行之前调用了很多次函数三并且距离值没有更新。

【问题讨论】:

  • 检查 jQuery when() 函数。 api.jquery.com/jQuery.when
  • 也许你可以从另一个函数调用一个函数?
  • 最好的方法完全取决于“任何其他距离计算 api”在做什么。
  • 我已经从这个问题中删除了 J 标签,因为这个问题与 J 语言无关。请在将来标记您的问题时更加小心。谢谢。
  • 利用 jquery 队列。见stackoverflow.com/questions/1095263/…

标签: javascript jquery ajax


【解决方案1】:

利用回调:

function first(tolat, tolon, fromlat, fromlon, callback) {
     if (typeof(callback) == 'function') {
        callback(distance);
     }
}

function second() { }
function third() { }

first("vartolat", "vartolon", "varfromlat", "varfromlon", function(distance) {
    alert(distance);
    second();
    third();
});

【讨论】:

  • 我喜欢这个,不知道如何使用回调。正在研究这个,谢谢。
  • 这些函数(和你的一样)被称为“异步函数”。回调会阻止其他函数在异步函数完成之前执行(如果使用得当)。不客气。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
相关资源
最近更新 更多