Domanda

I'm working with the new mapbox.js API, especially the event callback 'panned'. The callback is fired about 50-100 times when the user moves the map, which is way too much. What's the best way to get only the first and the last event (or only the last) out of this?

map.addCallback('panned', function(move) {
  console.log('panned');
});
È stato utile?

Soluzione

Use .setTimeout:

var timeout = null;
map.addCallback('panned', function (move) {
    timeout && window.clearTimeout(timeout);
    timeout = window.setTimeout(function () {
        console.log('panned')
    }, 100)
})

For the timeout time choose an appropriate time, which you have to find out by fiddling around with several values.

Altri suggerimenti

UnderscoreJS has a few useful functions.

Debounce might be best suited for you, based on what you describe: ... postpone its execution until after wait milliseconds have elapsed since the last time it was invoked

"Throttle" is also useful: "... will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with."

HTH

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top