Richard Greenwood
Richard Greenwood

Reputation: 1004

How to put a setTimeout() on map resize

I'm using an ImageWMS layer with ratio: 1.0, so my map requests are exactly the dimensions of the map <div>. If the user resizes the map slowly there can be dozens of map requests. I'd like to put a setTimeout() on the resize event to delay the map requests and hopefully reduce the number of requests. Any suggestions as to how I might do that?

Upvotes: 1

Views: 554

Answers (1)

Richard Greenwood
Richard Greenwood

Reputation: 1004

I ended up with the following, which delays updating the map's size (and thus making a request to the server) by half a second.

window.addEventListener('resize', function(e) {
    if (e) {
        e.stopImmediatePropagation()
        clearTimeout(window.updateSizeTimer)
        window.updateSizeTimer = setTimeout(function() {
          map.updateSize();
      }, 500);
    }
});

The event listener needs to be registered before creating the map object, otherwise stopImmediatePropagation() won't prevent the default OpenLayers resize handler from being invoked. window.updateSizeTimer can be any global variable, but it has to be persistent if it's to be cleared by clearTimeout()

Upvotes: 2

Related Questions