面试题答案
一键面试防抖(Debounce)
防抖的原理是在事件触发后,等待一定时间(例如300毫秒),如果这段时间内事件没有再次触发,则执行相应的操作。如果在等待时间内事件再次触发,则重新计算等待时间。这样可以避免短时间内频繁触发事件。
应用场景
适用于输入框搜索、窗口resize等场景,避免在用户还在输入或操作时就频繁发起请求。
代码实现
- 定义防抖函数
function debounce(func, delay) {
let timer;
return function() {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
- 在Vue项目中使用
<template>
<div>
<input v-model="inputValue" @input="debouncedSearch">
</div>
</template>
<script>
export default {
data() {
return {
inputValue: ''
};
},
created() {
this.debouncedSearch = debounce(this.search, 300);
},
methods: {
search() {
// 这里发起网络请求
console.log('发起搜索请求,关键词:', this.inputValue);
}
}
};
function debounce(func, delay) {
let timer;
return function() {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
</script>
节流(Throttle)
节流的原理是规定在一个单位时间内,只能触发一次事件。如果在这个时间间隔内多次触发事件,只有第一次或最后一次会生效。
应用场景
适用于滚动事件、鼠标移动事件等,避免短时间内大量触发事件导致性能问题。
代码实现
- 定义节流函数
function throttle(func, delay) {
let lastTime = 0;
return function() {
const context = this;
const args = arguments;
const now = new Date().getTime();
if (now - lastTime >= delay) {
func.apply(context, args);
lastTime = now;
}
};
}
- 在Vue项目中使用
<template>
<div @scroll="throttledHandleScroll">
<!-- 页面内容 -->
</div>
</template>
<script>
export default {
methods: {
handleScroll() {
// 这里发起网络请求,例如加载更多数据
console.log('滚动事件触发,处理加载更多等操作');
}
},
created() {
this.throttledHandleScroll = throttle(this.handleScroll, 300);
}
};
function throttle(func, delay) {
let lastTime = 0;
return function() {
const context = this;
const args = arguments;
const now = new Date().getTime();
if (now - lastTime >= delay) {
func.apply(context, args);
lastTime = now;
}
};
}
</script>