debounce限制多长时间才能执行一次,throttle限制多长时间必须执行一次,一个限制上限、一个限制下限
防抖
适用范围 input框实时搜索 防抖
function debounce(func, delay) {let timeout = null;.//闭包return function(e) {if(timeout){clearTimeout(timeout)}var context = this, args = argumentstimeout = setTimeout(function(){func.apply(context, args);},delay)};};@@@@ = debounce(fn, 380);
节流
适用范围在 比input, keyup更频繁触发的事件中,如resize, touchmove, mousemove, scroll。throttle 会强制函数以固定的速率执行。因此这个方法比较适合应用于动画相关的场景。
function throttle(fn, threshhold) {var timeoutvar start = new Date;var threshhold = threshhold || 160return function () {var context = this, args = arguments, curr = new Date() - 0clearTimeout(timeout)//总是干掉事件回调if(curr - start >= threshhold){console.log("now", curr, curr - start)//注意这里相减的结果,都差不多是160左右fn.apply(context, args) //只执行一部分方法,这些方法是在某个时间段内执行一次start = curr}else{//让方法在脱离事件后也能执行一次timeout = setTimeout(function(){fn.apply(context, args)}, threshhold);}}}var mousemove = throttle(function(e) {console.log(e.pageX, e.pageY)});// 绑定监听document.querySelector("#panel").addEventListener('mousemove', mousemove);throttle(fn,delay){let valid = truereturn function() {if(!valid){return false}var context = this, args = argumentsvalid = falsesetTimeout(() => {fn.apply(context, args)valid = true;}, delay)}}
