防抖 节流

56 阅读1分钟

防抖

<button @click="debouncedFetchData">请求</button>

const timeoutId = ref(null); 
function debounce(fn, delay) {
  return function(...args) {
    if (timeoutId.value) clearTimeout(timeoutId.value);
    timeoutId.value = setTimeout(() => {
      fn(...args);
    }, delay);
  };
}

function fetchData() {
  axios.get()  
    .then(response => {
      console.log(response.data);
    })
}

const debouncedFetchData = debounce(fetchData, 300); 

节流实现

<button @click="throttledFetchData">请求</button>

const lastCall = ref(0); 
function throttle(fn, delay) {
  return function(...args) {
    const now = new Date().getTime();
    if (now - lastCall.value < delay) return;
    lastCall.value = now;
    fn(...args);
  };
}

function fetchData() {
  axios.get()  //
    .then(response => {
      console.log(response.data);
    })
} 
const throttledFetchData = throttle(fetchData, 1000);