2010-10-27 21 views
0

我遇到以下問題:在JavaScript/jQuery中超時函數

我在我的網站上使用Google地圖。我已將以下eventListener附加到地圖本身:

google.maps.event.addListener(map, 'bounds_changed', scheduleDelayedCallback); 

每次有人拖動地圖時都會調用bounds_changed事件。我的問題是,在拖動過程中會多次調用它。現在我需要找到一種方法來調用回調函數,如果它沒有在最後一次調用,比方說750毫秒。

我這樣做是使用這兩個功能:

function fireIfLastEvent() { 
    var now = new Date().getTime(); 
    if (lastEvent.getTime() + 750 <= now) { 
     this_function_needs_to_be_delayed(); 
    } else { 
     $("#main").html('Lade...'); 
    } 
} 

function scheduleDelayedCallback() { 
    lastEvent = new Date(); 
    setTimeout(fireIfLastEvent, 750); 
} 

此方法適用於Chrome和Opera很大。在IE中它有時候起作用,在Firefox中它永遠不會起作用(即使750毫秒沒有通過,它也會調用這些函數)。

是否有堅定的方法來超時函數調用?

謝謝。

+0

什麼是'this_function_needs_to_be_delayed'? – SLaks 2010-10-27 15:29:18

+0

這是應該在bounds_changed事件上調用的實際函數。我把其他兩個函數放在兩者之間來創建這個僞超時。 - google.maps.event.addListener(map,'bounds_changed',this_function_needs_to_be_delayed); – user276289 2010-10-27 15:52:59

回答

0

這裏不需要超時。

function scheduleDelayedCallback() { 

    var now = new Date(); 

    if (now.getTime() - lastEvent.getTime() >= 750) { 
     // minimum time has passed, go ahead and update or whatever 
     $("#main").html('Lade...'); 
     // reset your reference time 
     lastEvent = now; 
    } 
    else { 
     this_function_needs_to_be_delayed(); // don't know what this is. 
    } 
} 

你對你想要發生的事情的解釋並不是最清楚的,所以讓我知道如果流程是錯誤的。

+0

工程就像一個魅力!謝謝! – user276289 2010-10-27 16:19:00