无法在具有参数的函数中实现去抖动

我正在尝试在每次用户在自动完成框中键入内容时调用的 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);

  }

}


莫回无
浏览 62回答 1
1回答

牧羊人nacy

当您debounceSearch在此代码块中启动时调用它,您实际上是在调用getAllIds.$scope.searchTextChange = function(searchText){&nbsp; debounceSearch(getAllIds(searchText),1000);&nbsp;}更好的方法是使范围searchTextChange去抖动,例如:$scope.searchTextChange = debounceSearch( function(searchText) {&nbsp; getAllIds(searchText);&nbsp;}, 1000);这将一起解决你的问题,并通过阅读代码清楚地表明它searchTextChange被去抖动(警告如果你有一些对this上下文的调用,你应该将回调绑定到 this 或使用箭头函数)const elem = document.getElementById('searchInput');const result = document.getElementById('results');// taken from: https://davidwalsh.name/javascript-debounce-functionfunction debounce(func, wait, immediate) {&nbsp; &nbsp; var timeout;&nbsp; &nbsp; return function() {&nbsp; &nbsp; &nbsp; &nbsp; var context = this, args = arguments;&nbsp; &nbsp; &nbsp; &nbsp; var later = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timeout = null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!immediate) func.apply(context, args);&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; var callNow = immediate && !timeout;&nbsp; &nbsp; &nbsp; &nbsp; clearTimeout(timeout);&nbsp; &nbsp; &nbsp; &nbsp; timeout = setTimeout(later, wait);&nbsp; &nbsp; &nbsp; &nbsp; if (callNow) func.apply(context, args);&nbsp; &nbsp; };};elem.addEventListener('keypress', debounce( search, 1000 ) );function search( e ) {&nbsp; results.innerText += 'You\'ve searched for ' + e.target.value;}<input type="text" id="searchInput" /><div id="results"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript