1 回答

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>
添加回答
舉報