【问题标题】:Timeout a function in JavaScript/jQueryJavaScript/jQuery 中的函数超时
【发布时间】:2010-10-27 15:26:48
【问题描述】:

我遇到了以下问题:

我在我的网站上使用 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 毫秒,它也会调用函数)。

有什么可靠的方法可以让函数调用超时?

谢谢。

【问题讨论】:

  • this_function_needs_to_be_delayed 是什么?
  • 这是应该在 bounds_changed 事件上调用的实际函数。我把另外两个函数放在中间来创建这个伪超时。 - google.maps.event.addListener(map, 'bounds_changed', this_function_needs_to_be_delayed);

标签: javascript jquery google-maps timeout


【解决方案1】:

这里不需要超时。

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

你对你想要发生的事情的解释不是最清楚的,所以如果流程有误,请告诉我。

【讨论】:

  • 像魅力一样工作!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 2016-09-24
  • 2017-10-27
  • 1970-01-01
  • 2017-06-25
  • 2016-03-15
相关资源
最近更新 更多