这种操作类型叫节流阀,我写个简单的例子吧:
var throttle = function(func, wait) { var createThrottle = function(f, t) { var last, timer; return function() { var args = Array.prototype.slice.call(arguments); var _this = this, now = new Date().getTime(); if (typeof last === 'undefined') { last = now; return func.apply(_this, args); } if (now - last > wait) { func.apply(_this, args); last = new Date().getTime(); }else { clearTimeout(timer); timer = setTimeout(function() { func.apply(_this, args); last = new Date().getTime(); }, wait - now + last); } }; }; return createThrottle(func, wait); }; var num = 0; document.getElementById('countspan').innerHTML = num; function countNumber(){ num++; document.getElementById('countspan').innerHTML = num; } var throttled = throttle(countNumber, 1000);
完整的demo,到plunker去看