js中防抖函数
<body>
<input type="text">
</body>
<script>
let input = document.querySelector('input')
input.oninput = debounce(val,2000)
function val(e) {
console.log(e.target.value);
}
function debounce(fn,delay=2000) {
let timer = null
return function() {
let args = arguments
let _this = this
clearTimeout(timer)
timer = setTimeout(()=> {
fn.apply(_this,args)
},delay)
}
}
</script>
js中节流函数
function throttle(fn, delay) {
let timer = null;
return function () {
let args = arguments;
let _this = this;
if (!timer) {
timer = setTimeout(() => {
fn.apply(_this, args);
timer = null;
}, delay);
}
};
}
在vue中使用防抖和节流,只需要新建一个向外暴露的js文件
在vue文件中引入