语法将setTimeout添加到回调函数

时间:2013-01-22 22:32:40

标签: javascript google-maps-api-3 asynchronous syntax settimeout

我正在尝试制作以下内容'我将在哪里进入这些目标位置的x英里'异步功能(效果很好)也在执行之间等待。谷歌地图流程对速度有限制,在“Over_Query_limit”开始绘制地图之前,我可以绘制10条以上的路线。

我知道服务条款(2500 /天),我没有打破它们。

它位于一个循环中,包含来自中心点(pt)的所需目标数组(endPoints) 请问这是什么语法? 我已经在这个和其他网站上阅读了很多内容,并且可以看到该函数应该放在引号中,但是使用异步调用我不知道如何。

你可以看到我的不良尝试(注释掉)

var delay=100;
for (var i = 0; i < endPoints.length; i++) {
    //setTimeout(function() {
        howfar(pt,endPoints[i],i,function(i,status,endPoint) {
            //process results
        });
    //},delay;
}

function howfar(from,to,i,callback) {
    //get the endpoint from the directions service
    callback.call({},i,status,endPoint);
}

始终感谢您寻找和帮助

2 个答案:

答案 0 :(得分:1)

确切的语法如下所示:

var delay = 100; // in milliseconds, 100 is a tenth of a second
setTimeout(function() {
    howfar(pt,endPoints[i],i, function(i,status,endPoint) {
        //process results
    });
}, delay);
不过,快速的谷歌可能会把它变成现实。

答案 1 :(得分:1)

如果我理解你的问题,你需要等到howfar函数返回加上一个固定的延迟,然后才处理数组中的下一个endPoint

我通常会设置一个迭代器函数,该函数会自行调度,直到没有其他项目要处理。类似的东西:

var delay = 100;
var i = 0;
//define a helper function
var measureNext = function() {

   howfar(pt, endPoints[i], i, function(i,status,endPoint) {
     //process results

     //if there are still unprocessed items in the array, schedule
     //the next after {delay} milliseconds
     if(i++ < endPoints.length) {
       setTimeout(measureNext, delay);
     }
   });

};

//start with the first argument
measureNext();
相关问题