函数防抖 用于搜索比较多
/**
* 函数防抖 设定时间内多次事件一次相应
*
* @param {Function} callback
* @param {number} time
* @returns
*/
export function debounce(callback, time){
let timeId = null;
return function(e){
if(timeId !== null){
clearTimeout(timeId);
}
timeId = setTimeout(() => {
callback.call(this, e);
timeId = null;
}, time);
}
}
函数节流:主要用于onmousemove,onscroll事件
- 函数节流 函数每隔一段时间触发一次
*
* @param {Function} fn
* @param {number} gap
* @returns
*/
function throttle(fn, gap) {
let begin = Date.now();
return function () {
let now = Date.now();
if (now - gap > begin) {
begin = now;
var context = this;
var args = arguments;
fn.apply(context, args);
}
};
}
标题调用方法:
函数防抖和节流的调用方法都是差不多的
事件注册
<button @click="dianji('2')">点击</button>
引入
import { debounce } from "@/utils/validate";
调用
methods: {
dianji: debounce((e) => {
console.log("11");
}, 500),
}