1 // 防抖 2 export function _debounce(fn, delay) { 3 4 var delay = delay || 200; 5 var timer; 6 return function () { 7 var th = this; 8 var args = arguments; 9 if (timer) { 10 clearTimeout(timer); 11 } 12 timer = setTimeout(function () { 13 timer = null; 14 fn.apply(th, args); 15 }, delay); 16 }; 17 } 18 // 节流 19 export function _throttle(fn, interval) { 20 var last; 21 var timer; 22 var interval = interval || 200; 23 return function () { 24 var th = this; 25 var args = arguments; 26 var now = +new Date(); 27 if (last && now - last < interval) { 28 clearTimeout(timer); 29 timer = setTimeout(function () { 30 last = now; 31 fn.apply(th, args); 32 }, interval); 33 } else { 34 last = now; 35 fn.apply(th, args); 36 } 37 } 38 }
使用:
1. 先引入 import { _debounce, _throttle } from ‘(当前代码所在位置)‘
2. 在methods中使用
1 methods: { 2 changefield: _debounce(function(_type, index, item) { 3 // do something ... 4 }, 200) 5 }
如此使用即可!(原理继续下翻)
---------------------------------分割线------------------------------
产生原因:
基于上述原因,节流和防抖的概念也就出来了:
函数节流的应用场景
频繁触发的函数,在规定时间内,只让最后一次生效,前面的不生效。
原理:第一次调用函数,创建一个定时器,在指定的时间间隔之后运行代码。当第二次调用该函数时,它会清除前一次的定时器并设置另一个。如果前一个定时器已经执行过了,这个操作就没有任何意义。然而,如果前一个定时器尚未执行,其实就是将其替换为一个新的定时器,然后延迟一定时间再执行。
例:
注: 转载于https://www.jianshu.com/p/c63b1d1fb0da
原文:https://www.cnblogs.com/workJiang/p/14504943.html