ama2
ama2

Reputation: 2681

JavaScript onresize event fires multiple times

I'm having some trouble trying running a function only once when onresize event is triggered, I have looked at this questions DOM onresize event but I'm not using jQuery and can't get that function to work without. Any suggestions?

Upvotes: 2

Views: 6601

Answers (2)

Bergi
Bergi

Reputation: 664599

You could use the debounce implementation from underscore:

  function debounce(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      if (immediate && !timeout) func.apply(context, args);
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  }
  window.onresize = debounce(function() {
      // Your code here
  }, 500);

Or use the library from the linked question. Without jQuery, it is Cowboy.debounce(...).

Upvotes: 4

Arlen Anderson
Arlen Anderson

Reputation: 2496

The resize event is called once for every frame during the resizing operation. If you want to call it when resizing is finished, just set timer with a callback function.

var timeOut = null;

window.onresize = function(){
    if (timeOut != null)
        clearTimeout(timeOut);

    timeOut = setTimeout(function(){
        // YOUR RESIZE CODE HERE
    }, 500);
};

Upvotes: 11

Related Questions