亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法在具有參數的函數中實現去抖動

無法在具有參數的函數中實現去抖動

莫回無 2022-10-13 19:15:55
我正在嘗試在每次用戶在自動完成框中鍵入內容時調用的 API 函數中實現去抖動。但不知何故,當我輸入一些東西時,它會調用主 API 函數而不是去抖函數。下面是代碼:$scope.searchTextChange = function(searchText){debounceSearch(getAllIds(searchText),1000); //getAllIds get called everytime upon keyboard input}const debounceSearch= (callback, delay) => {  let timeout = null;  return (...args) => {    const next = () =>     callback(...args);    clearTimeout(timeout);    timeout = setTimeout(next, delay);  }}
查看完整描述

1 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

當您debounceSearch在此代碼塊中啟動時調用它,您實際上是在調用getAllIds.


$scope.searchTextChange = function(searchText){

  debounceSearch(getAllIds(searchText),1000); 

}

更好的方法是使范圍searchTextChange去抖動,例如:


$scope.searchTextChange = debounceSearch( function(searchText) {

  getAllIds(searchText); 

}, 1000);

這將一起解決你的問題,并通過閱讀代碼清楚地表明它searchTextChange被去抖動(警告如果你有一些對this上下文的調用,你應該將回調綁定到 this 或使用箭頭函數)


const elem = document.getElementById('searchInput');

const result = document.getElementById('results');


// taken from: https://davidwalsh.name/javascript-debounce-function

function debounce(func, wait, immediate) {

    var timeout;

    return function() {

        var context = this, args = arguments;

        var later = function() {

            timeout = null;

            if (!immediate) func.apply(context, args);

        };

        var callNow = immediate && !timeout;

        clearTimeout(timeout);

        timeout = setTimeout(later, wait);

        if (callNow) func.apply(context, args);

    };

};


elem.addEventListener('keypress', debounce( search, 1000 ) );


function search( e ) {

  results.innerText += 'You\'ve searched for ' + e.target.value;

}

<input type="text" id="searchInput" />

<div id="results"></div>


查看完整回答
反對 回復 2022-10-13
  • 1 回答
  • 0 關注
  • 77 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號