[英]Timeout a function in 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毫秒,它也會調用函數)。
有什么堅決的方法可以使函數調用超時?
謝謝。
您不需要在這里超時。
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.
}
}
您對要發生的事情的解釋不是最清楚,因此請讓我知道流程是否錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.