vue 앱에서 JavaScript로 디바운스된 함수 호출

6021 단어 vuewebdevjavascript
여기서는 디바운스의 개념 또는 이와 유사한 개념에 대해 이야기하고 싶습니다.

그래서 끝점에는 호출할 수 있는 호출의 양을 제한하는 미들웨어가 있으므로 끝점에 대한 API 호출 수를 제한해야 하는 필요성에 직면했습니다. (각 클라이언트에 대한 초당 호출, 초당 두 번 이상의 API 호출에 대해 오류가 발생합니다). 따라서 이러한 종류의 API도 사용해야 하는 경우 이 게시물이 도움이 될 것입니다.

해결책은 JavaScript setTimeout 함수 덕분에 오히려 간단합니다. 따라서 이 API에 의해 설정된 제한에 따라 API 호출 빈도를 초당 최대 1회로 제어하는 ​​방법이 필요했습니다.

검색 기능을 구현하려면 이 API를 호출해야 했습니다. 이는 앱 사용자가 키 입력(검색을 위해 입력할 때)마다 API를 호출함을 의미합니다. 이로 인해 api는 평균 사용자 유형으로 초당 하나 이상의 문자로 자주 호출됩니다.

이에 대한 솔루션 요약은 “사용자가 만드는 모든 API 요청에 대해 1초 미만의 요청이 있는지 확인합니다. 있는 경우 새 api 요청을 1초 후에 "연기"하고 그렇지 않으면 즉시 api를 호출합니다."

이 솔루션은 vuejs 앱에 맞게 조정되지만 다른 스택에서도 사용할 수 있습니다.

이 솔루션을 구현하려면 다음이 필요합니다.

<input type="text" @input="handleSearch" placeholder="search"/>



data() {
  return {
    can_start:true
    search_timeout:null
    can_start_timeout:null,
    delay:1000
}



methods:{
  async search(){
    this.resetCanStart();
    await yourThrottledApi();
    // the api endpoint with request limit of 1 
    // request per second
  },

  deferredSearch() {
    if (this.search_timeout) clearTimeout(this.search_timeout);
    // this delete pending api request, so we don't have more 
    // than one pending request queued

    this.search_timeout = setTimeout(() => this.search(), 
    this.delay);
   // create a pending request which is called after a delay

  },

  handleSearch() {
     this.can_start ? this.search() : this.deferredSearch();
    // this handles the search such that search api request is 
    // called immediately if 'can_start' is true, else the
    // request is delayed for a second

  },

  resetCanStart() {
    this.can_start = false;

    if(this.can_start_timeout)
    clearTimeout(this.can_start_timeout);

    this.can_start_timeout = setTimeout(() => {
       this.can_start = true;
    }, this.delay);

    // this set 'can_start' to false immediately after a request, 
    // and then set it back to true after a delay (1 second) 
    // (i.e it blocks another request from being made by setting 
    // 'can_start' to false, then allows new request only after 1 
    //  second by setting 'can_start' to true
}


}



솔루션의 의미
  • 예를 들어 api가 1초 미만(예: T초)에 결과를 반환하는 경우 결과적으로 즉시 이루어진 api 호출은 강제로 잠시(1초 - T초) 지연됩니다.

  • 이 두 조건이 모두 충족되면 일부 API 요청이 이루어지지 않습니다.
  • 현재 요청이 마지막 요청 후 1초 이내에 이루어집니다
  • .
  • 현재 요청
  • 이후 1초 이내에 다른 요청이 이루어집니다.

    좋은 웹페이지 즐겨찾기