Resize flexlslider at the end of window resize

490 views Asked by At

As you may know putting anything code in window.resize will make it execute for every pixel the user moves the window for, a lot of calls basically.

What it means is flexslider is resizing it self for every pixel moved, this slows the browser down due to heavy execution of JS and sometimes makes the slider go haywire. Granted no one is just sitting there resizing the browser all day but still it's a lot of unnecessary code execution.

$( window ).resize(function() {
      var slider1 = $('#slider1').data('flexslider');
      slider1.resize();

});

The underscore debounce function works well to detect the end of a resize however it does not work with flexslider.

http://davidwalsh.name/function-debounce

 $(window).resize(_.debounce(function(){

      console.log('resizing');
      var slider1 = $('#slider1').data('flexslider');
      slider1.resize();

 }, 500));

I can see in the console it is still getting called hundreds of times due to the slider.resize();

Essentially is there a way to detect an end of window resize and then call flexslider?

1

There are 1 answers

0
Juank On

I'm not familiar with the debounce function but you can easily do this by hand and you'll be able to tweak the behavior

 function doResize(){
    console.log('ended resizing');
    var slider1 = $('#slider1').data('flexslider');
    slider1.resize();
 }

 var timeout;

 $(window).resize(function(){
    console.log('resizing');
    clearTimeout(timeout);
    timeout = setTimeout(doResize, 100); // tweak this delay to best suit your needs
 }, 500));

What this does is that it clears and sets a timeout of 100ms upon each resize event. If another resize event is called before 100ms, the timeout is reset to another extra 100ms and does not fire. This way only the last resize event will trigger the doResize function. But keep in mind that a "last resize event" is considered to be one that has no resize events called after 100ms, in effect, debouncing it.