views:

23

answers:

1

Hello everyone

I've got the following problem:

I'm using Google Maps on my site. I've attached the following eventListener to the map itself:

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

The event bounds_changed is called every time someone drags the map. 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.

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. In IE it works sometimes, in Firefox it never works (it calls the functions even if the 750 milliseconds haven passed).

Is there any rock-solid way to timeout a function call?

Thanks.

A: 

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.

lincolnk
Works like a charm! Thank you!