2

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?

Community
  • 1
  • 1
ama2
  • 2,611
  • 3
  • 20
  • 28
  • Post some code - from the top of my head, use a boolean? – eric.itzhak Jun 21 '12 at 21:50
  • 1
    The linked answer doesn't need jQuery to work, pure JavaScript do. Read again – Alexander Jun 21 '12 at 21:51
  • $(window).resize($.debounce(1000, function() { // Handle your resize only once total, after a one second calm. ... })); I have tried using this without jquery but it doesn't work, I'm using this inside a firefox extension – ama2 Jun 21 '12 at 21:53
  • you can't use jQuery's namespace (`$`) as in `$(window).resize` if you don't have jQuery, instead you'll have to bind it in the `window.onresize = function() {` (or another listener) and use the `Cowboy` namespace as described in the author's page. I'd personally use a `setTimeout` and `clearTimeout`. – Fabrício Matté Jun 21 '12 at 21:56

2 Answers2

11

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);
};
Arlen Anderson
  • 2,486
  • 2
  • 25
  • 36
4

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(...).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375