防抖
//debounce.js
export const debounce = (function () { //操作防抖
let timer, flag = true;
return function (callback, ms, im=false) {
// 立即执行
if(im) {
if (flag){
callback();
flag = false;
}else {
clearTimeout(timer);
timer = setTimeout(() => {
callback();
flag = true
}, ms)
}
}else { //延迟执行
clearTimeout(timer)
timer = setTimeout(callback, ms)
}
}
})()
组件的使用
import {debounce} from '../../util/debounce.js'
mothods: {
changeDoor (state,data) {
console.log('打开门',state,data)
}
openDoor () {
debounce(() => { //防抖
this.changeDoor('open',this.api_data.POWER)
}, 500)
}
}
节流
函数节流是在一定时间内只执行一次
//节流
const throttle = (function () {
let flag = true;
return function (f, t, im = false) {
if (flag) {
flag = false
im && f()
setTimeout(() => {
!im && f()
flag = true
}, t)
}
}
})()
export { throttle }
clickFn() {
throttle(() => {
this.jie()
}, 1000,true)
},