From
函数节流:常用于onresize,scroll,mousemove,mousehover等连续触发的事件(隔断时间触发一次)。
方法:
eg.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| window.onscroll = function() { console.log('scoll滑动'); throttle(count); };
function count() { console.log('函数调用'); }
function throttle(method, context) { clearTimeout(method.tId); method.tId = setTimeout(function() { method.call(context); }, 300); }
var time = +new Date(); function count() { console.log('函数调用:' + (+new Date() - time)); }
var throttle = function(fn, delay, mustRun) { var timer = null, previous = null;
return function() { var now = +new Date(), context = this, args = arguments; if(!previous) previous = now; var remaining = now - previous; if(mustRun && remaining >= mustRun){ fn.apply(context, args); previous = now; } else { cleaerTimeout(timer); timer = setTimeout(function() { fn.apply(context, args); }, delay); } }; };
window.onscroll = throttle(count, 500, 1000);
|