Nouvelle méthode (tips: utilisez celle-ci)

Source: Debouncing and Throttling in JavaScript

Version PDF: Debouncing and Throttling in JavaScript


Ancienne méthode

…et en fait j’ai jamais réussi à la faire fonctionner.

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

Problème:

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:

The event ‘idle’ 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 function to be executed only after the user has stopped to move the map during some time period (for example 500ms).

Solution

A l’addListener pour l’événement idle de l’API Google Maps, on déclare une fonction qui contiendra juste notre appel à la fonction debounce: