2016-02-12 63 views
0

调整窗口大小后,只能运行5次函数吗?当您再次调整大小时,再次运行该功能5次。在调整大小后运行jQuery函数5次

$(window).bind('resize', function() { 
    setTimeout(function(){ 
     var slider = $('.wrapper .flexslider').data('flexslider'); 
     slider.resize(); 
    }, 500); 
}); 

该函数每0.5秒运行一次。但浏览器无法处理它,并且一次运行此功能不足以正确调整flexslider的大小(我不知道为什么)。

+0

它的运行更多的时间比你想象的。 'resize'处理程序不会只运行一次。在手动调整大小时,您将应用100个'setTimeout' – charlietfl

+0

是否有替代方法? – hgnl96

+1

我认为真正令人怀疑的是你需要多次调用'resize()'。可能值得研究为什么你需要这样做。 – Gilgamesh

回答

0

是的。向你的函数添加一个回调函数,并且根据需要多次递归地调用它。

0

以下是注释中提到的去抖功能的示例。

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); 
      }; 
      var callNow = immediate && !timeout; 
      clearTimeout(timeout); 
      timeout = setTimeout(later, wait); 
      if (callNow) func.apply(context, args); 
     }; 
    }; 

    var myEfficientFn = debounce(function() { 
     // Your resize code here, only fired once 
    }, 500); 

    window.addEventListener('resize', myEfficientFn);