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>
添加回答
举报