简体   繁体   中英

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?

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);
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM