js文件 utils.js
// 防抖
export function debounce (fn, delay) {
var timer
return function () {
var th = this
var args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function () {
timer = null
fn.apply(th, args)
}, delay)
}
}
// 节流
export function throttle (fn, interval) {
var last
var timer
return function () {
var th = this
var args = arguments
var 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)
}
}
}
vue文件
import { debounce, throttle } from '../common/js/utils'
methods: {
toSearch2: debounce(function (value) {
console.log('防抖', value)
}, 500),
toSearch1: throttle(function (value) {
console.log('节流', value)
}, 500),
}