js中的防抖节流函数以及使用场景
let timer = null
export function debounce(calback, delay=200) {
return function() {
clearTimeout(timer)
timer = setTimeout(() => {
calback && calback.apply(this)
}, delay)
}
}
<input type="text" v-model="inputs" />
data() {
return{
inputs: ''
}
},
watch: {
inputs(val) {
debounce(() => {
console.log(val);
})();
},
}
let timer = null
export function throttle(fn, delay = 200) {
return () => {
if (timer) return
timer = setTimeout(() => {
fn && fn.apply(this, arguments)
timer = null
}, delay)
}
}
import { throttle } from "./utils/throttle";
onMounted(() => {
window.addEventListener("scroll", () => {
throttle(() => {
console.log(11111);
}, 500)();
});
});
let tamp = 0;
export function throttle(num = 2000) {
const nowTamp = Date.now();
if(nowTamp - tamp < num) {
return false;
}
tamp = nowTamp;
return true;
}