Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to respond to a Javascript event only if it is fired once and then not fired again during some time period?

In my application I listen to the Google Maps API 'bounds_changed' event to send an ajax request to update some div on the web page depending on the new boundaries of the map:

google.maps.event.addListener(map, 'bounds_changed', function() {
  // here goes an ajax call
}

The event 'bounds_changed' is fired with a high frequency when the user drag the map around. So much that there are too many ajax requests sent to the server.

Basically I would like to make the ajax call only after the user has stopped to move the map during some time period (for example 500ms). I am not very experienced with Javascript and tried to achieve this with setTimeout and clearTimeout but without success.

Any idea would be appreciated :)

like image 285
Florent2 Avatar asked Jul 15 '10 23:07

Florent2


People also ask

Which is the most preferred way of handling events in JavaScript?

The addEventListener method is the most preferred way to add an event listener to window, document or any other element in the DOM. There is one more way called “on” property onclick, onmouseover, and so on.

What happens if an event occurs and there is no event handler to respond to the event?

TF: if an event occurs and there is not event handler to respond to that event, the event ins ignored.


1 Answers

google suggests using another listener ...

google.maps.event.addListener(map, 'idle', showMarkers);

quote "Note that you could listen to the bounds_changed event but it fires continuously as the user pans; instead, the idle will fire once the user has stopped panning/zooming." /quote

see

http://code.google.com/apis/maps/articles/toomanymarkers.html#gridbasedclustering

like image 138
camel Avatar answered Nov 15 '22 16:11

camel