简体   繁体   English

JavaScript / jQuery中的函数超时

[英]Timeout a function in JavaScript/jQuery

I've got the following problem: 我遇到以下问题:

I'm using Google Maps on my site. 我在自己的网站上使用Google地图。 I've attached the following eventListener to the map itself: 我已将以下eventListener附加到地图本身:

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

The event bounds_changed is called every time someone drags the map. 每当有人拖动地图时,都会调用bounds_changed事件。 My Problem is, that it is called several times during the drag process. 我的问题是在拖动过程中多次调用它。 Now I need to find a way to call the callback function only, if it wasn't called during the last, let's say, 750 milliseconds. 现在,我需要找到一种方法来仅调用回调函数,如果在上一个(例如750毫秒)内未调用该函数。

I did this using these two functions: 我使用以下两个功能完成此操作:

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

This method works great in Chrome and Opera. 此方法在Chrome和Opera中效果很好。 In IE it works sometimes, in Firefox it never works (it calls the functions even if the 750 milliseconds haven passed). 在IE中,它有时可以工作,在Firefox中,它却永远无法工作(即使经过了750毫秒,它也会调用函数)。

Is there any rock-solid way to timeout a function call? 有什么坚决的方法可以使函数调用超时?

Thanks. 谢谢。

You shouldn't need a timeout here. 您不需要在这里超时。

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.
    }
} 

Your explanation of what you want to happen isn't the clearest so let me know if the flow is wrong. 您对要发生的事情的解释不是最清楚,因此请让我知道流程是否错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM