抖动
涵义
在一个周期结束后触发,如果周期结束前被调用,则重置周期。
function debounce(handler, period, ...arg){let timer;return function(evt){if(timer) {clearTimeout(timer);timer = setTimeout(function(){timer = null;handler.call(this, evt, ...arg)}, period)} else {timer = setTimeout(function(){handler.call(this, evt, ...arg)}, period)}}}
节流
涵义
在一个周期内,无论调用多少次,只触发一次。
function throttle(handler, delay = 200, ...args) {let timer, last=0,return function (evt) {let now = Date.now()if (now - last > delay) {last = now;handler(evt, ...args)}}}
