防抖
/*
* fun [function] 需要防抖的函数
* delay [number] 毫秒,防抖期限值
*/
function debounce(fun, delay = 300) {
let timer;
return function () {
let ctx = this
let args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
timer = null
fun.apply(ctx, args)
}, delay)
}
}
节流
/*
* fun [function] 需要节流的函数
* delay [number] 毫秒,节流期限值
*/
function throttle(fun, interval = 300) {
let last;
let timer;
return function () {
let ctx = this
let args = arguments
let now = new Date()
if (last && now - last < interval) {
clearTimeout(timer)
timer = setTimeout(function () {
last = now
}, interval)
} else {
last = now
fun.apply(ctx, args)
}
}
}
使用
onLoad: function (options) {
this.formSubmit = throttle(this.formSubmit,3000)
},
formSubmit(e){ // 处理确认添加
}