防抖和节流
1.防抖:在一段时间内函数只会执行一次,如果在这个时间段内再次触发函数,则重新计算函数执行时间(可以用作提交事件,防止用户重复提交)
function debounce (fn, delay) { let timer return function () { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { fn() }, delay) }
2.节流:在一段时间内,函数最多可以触发一次执行(滚动加载的时候,当滑动到底部时,一直滑动那么每隔一定时间就会执行一次加载)
function throttle (fn, delay) { let isThtottle = ref(true) return () => { if (!isThtottle.value) return isThtottle.value = false setTimeout(() => { fn() isThtottle.value = true }, delay) }
或者
npm install throttle-debounce --save
import { throttle } from "throttle-debounce"//节流
import { debounce } from "throttle-debounce"//防抖