기본 콘텐츠로 건너뛰기

[javascript] 지연 실행(debounce) 함수 만들기

지연 실행 함수(debounce) 만들기


.vue 파일

<template>
  ...
  <input type="text" class="keyword_input" placeholder="키워드를 입력하세요" :value="info.keyword"
       @input="info.keyword = $event.target.value" @keyup="searchUp">
  ...
</template>

<script setup>
import { ref } from "vue"

const info = ref({
   keyword: "", // 검색어
})

// 입력할 때마다 이벤트 보내지 않게
const debounce = (fn, delay) => {
  let timer;
  return (...args) => {
    if(timer) {
      clearTimeout(timer);
    }
    const context = this;
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  }
}
const searchUp = debounce(() => {
  console.log(info.value.keyword);// 타이핑이 0.4초 멈추면 실행
}, 400);
</script>

debounce 함수 사용하기


끝.