在工具函数中定义防抖与节流函数
/**
* 防抖
* @param {*} fn
* @param {*} delay
* @returns
*/
export function debounce(fn, delay = 300) {
var timeID = null;
return function () {
clearTimeout(timeID);
timeID = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}
/**
* 节流
* @param {*} fn
* @param {*} delay
* @returns
*/
export function throttle(fn, delay) {
let valid = true;
return function () {
if (valid) {
setTimeout(() => {
fn.apply(this, arguments);
valid = true;
}, delay);
valid = false;
}
};
}
如何调用在项目中
<script>
import { debounce, throttle } from "../../assets/utils/webtools";
export default {
methods: {
antiShake: debounce(function () {
console.log("防抖");
}, 1000),
throttling: throttle(function () {
console.log("节流");
}, 1000),
},
};
</script>