节流
在单位时间内频繁触发事件,只生效一次(只有第一次生效)
应用场景: ① 多少秒之后获取验证码、② resize 事件、③ scroll 事件等
基本使用
vue
<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
import { throttle } from 'vue-hkp-ui'
onMounted(() => {
document.onscroll = throttle(showPosition, 1000)
})
onUnmounted(() => {
// 移除键盘切换事件
document.onscroll = null
})
function showPosition () {
const scrollTop = document.body.scrollTop || document.documentElement.scrollTop
console.log('滚动条位置:' + scrollTop)
}
</script>内部方法
vue
<script setup lang="ts">
function throttle (fn: Function, time = 300): any {
let activeTime:any = null;
return (...args) => {
const context = this;
const current = Date.now();
if (current - activeTime >= time) {
fn.call(context, ...args);
activeTime = Date.now();
}
};
}
</script>