簡體   English   中英

添加setTimeout以與回調函數一起使用的語法

[英]syntax to add setTimeout to function with callback

我正在嘗試執行以下“異步操作(效果很好)”,以便“在到達目標位置的x英里處”。 Google Maps進程對速度有限制,在“ Over_Query_limit”開始在地圖上繪制之前,我可以繪制的路線要多於10條。

我知道服務條款(每天2500個),我沒有違反這些條款。

它與一個從中心點(pt)到的所需目的地(終點)陣列成一個循環,請問實現此操作的語法是什么? 我在這個站點和其他站點上已經讀了很多書,可以看到該函數應該用引號引起來,但是通過異步調用我看不到如何做。

你可以看到我的糟糕嘗試(注釋掉了)

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);
}

一如既往的感謝您的關注和幫助

確切的語法如下所示:

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);

不過,一個快速的Google會證明這一點。

如果我理解正確你的問題,你需要等到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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM