// 防抖 export const debounce= (func, wait) => { var timeout; return function () { var context = this; var args = arguments; clearTimeout(timeout) timeout = setTimeout(function(){ func.apply(context, args) }, wait); } }; // 节流 export const throttle = (fn, wait) => { let canRun = true; // 通过闭包保存一个标记 return function () { if (!canRun) return; // 在函数开头判断标记是否为true,不为true则return canRun = false; // 立即设置为false setTimeout(() => { // 将外部传入的函数的执行放在setTimeout中 fn.apply(this, arguments); // 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。当定时器没有执行的时候标记永远是false,在开头被return掉 canRun = true; }, wait); }; } ////////////////////////////////////////////////////////// .vue文件中引用两个方法后直接使用 methods:{ clickFun: throttle (function(){ ...........逻辑代码......... },1000), }
原文:https://www.cnblogs.com/tutao1995/p/12620628.html