节流
utils/index.js
export function debounce(func, wait, immediate) {let timeout, args, context, timestamp, resultconst later = function () {// 据上一次触发时间间隔const last = +new Date() - timestamp// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 waitif (last < wait && last > 0) {timeout = setTimeout(later, wait - last)} else {timeout = null// 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用if (!immediate) {result = func.apply(context, args)if (!timeout) context = args = null}}}return function (...args) {context = thistimestamp = +new Date()const callNow = immediate && !timeout// 如果延时不存在,重新设定延时if (!timeout) timeout = setTimeout(later, wait)if (callNow) {result = func.apply(context, args)context = args = null}return result}}
使用 debounce
<template><div><button @click.stop="pointListChange(ztBoolean,4)">按钮<button></div></template><script>import { debounce } from '../utils/index'export default {methods:{/* 不要使用箭头函数 否则this会丢失 */pointListChange:debounce(function(status, index) {this.doPointListChange(status, index)}, 500, true),doPointListChange(status, index){...doSomething}}}</script>
另一种实现方法
export function _debounce(fn, delay = 200) {//防抖var timer;return function () {var th = this;var args = arguments;if (timer) {clearTimeout(timer);}timer = setTimeout(function () {timer = null;fn.apply(th, args);}, delay);};}
使用
<template><div><button @click.stop="ShowRspDevices()">按钮<button></div></template><script>import { _debounce } from '../../utils/debounce'export default {methods:{/* 不要使用箭头函数 否则this会丢失 */ShowRspDevices(val){this._debounceFun(val);},/* 不要使用箭头函数 否则this会丢失 */_debounceFun: _debounce(function(val){this.isShowRspDevices = val;this.initRsp();},500),}}</script>
