函数节流 和函数防抖定义在公共的工具函数库中:
utils.js文件
/**
* 函数节流
* @param fn
* @param interval
* @returns {Function}
* @constructor
*/
export function _throttle(fn, time) {
let last
let timer
const interval = time || 200
return function() {
const th = this
const args = arguments
const now = +new Date()
if (last && now - last < interval) {
clearTimeout(timer)
timer = setTimeout(function() {
last = now
fn.apply(th, args)
}, interval)
} else {
last = now
fn.apply(th, args)
}
}
}
// 防抖
export function _debounce(fn, wait) {
const delay = wait || 200
var timer
return function() {
const th = this
const args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function() {
timer = null
fn.apply(th, args)
}, delay)
}
}
2、在vue组件中使用示例
import { _throttle } from '@/utils'
methods: {
getChangingData: _throttle(function(val) {
this.activeItem.x = val.x
this.activeItem.y = val.y
this.activeItem.width = val.width
this.activeItem.height = val.height
this.activeItem.type = val.type
this.activeItem.id = val.id // id其实就是数组的索引值index
this.imgVidiolistInfo = this.items[this.activeItem.id].units
}, 200),
}