防抖动函数和节流函数
作者:互联网
防抖动函数是为了在类似连续点击事件中只在最后一次触发具体逻辑;
节流函数是为了间隔一段时间执行具体逻辑
let btn = document.getElementById("btn"); //防抖,执行性一次,每次调用间隔小于定时间隔 function debounce(fn,wait){ var timer = null; return function () { var args = arguments; if(timer){ clearTimeout(timer); } timer = setTimeout(function(){ fn.apply(this,Array.prototype.slice.call(args,0)); },wait); } } //节流函数,每隔一段时间执行一次 function throttle(fn,wait) { var timer = null; return function(){ /* if(!timer){ timer = setTimeout(()=>{ fn.apply(this,Array.prototype.slice.call(arguments,0)); timer = null; },wait) }*/ var args = arguments; var current = this; if(!timer){ timer = setTimeout(function(){ /* console.log(this == current); // true console.log(arguments == args); // false */ fn.apply(current,Array.prototype.slice.call(args,0)); timer = null; },wait); } } } function action(a){ console.log((new Date()).getSeconds()); } //连续点击按钮测试 //btn.onclick = throttle(action,1000); btn.onclick = debounce(action,1000);
标签:function,args,函数,防抖动,timer,var,wait,fn,节流 来源: https://www.cnblogs.com/zhanglw456/p/10614480.html