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:
1 2 3 |
google.maps.event.addListener(map, 'idle', function() { // here goes an ajax call } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function debounce(func, threshold, execAsap) { var timeout; return function debounced () { var obj = this, args = arguments; function delayed () { if (!execAsap) func.apply(obj, args); timeout = null; }; if (timeout) clearTimeout(timeout); else if (execAsap) func.apply(obj, args); timeout = setTimeout(delayed, threshold || 100); }; } |
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:
1 |
google.maps.event.addListener(mapApi.mapObj, 'idle', topic_onIdleDebounce); |
1 2 3 4 5 |
function topic_onIdleDebounce() { console.log('%c [topic_onIdleDebounce]', 'background: tomato'); debounce(topic_onIdle(), 300, true); } |
1 2 3 4 5 |
function topic_onIdle() { console.log('%c [topic_onIdle]', 'background: tomato'); // Tout le code à exécuter une fois que l'événement idle s'est déclenché pour la dernière fois dans les limites du timeout (300) défini dans notre fonction topic_onIdleDebounce } |