简体   繁体   中英

How to cancel debounced inside function with Lodash?

I'm implementing a feature, allow user typing for searching automatically. It's working properly for now.

To improve this function, I would like to support user press Enter then searching Ajax request must be called immediately.

I had read Lodash documentation. It says I can call debounced.flush . OK for now. Assign the method to variable.

  const debounced = _.debounce((event) => {
    // Call ajax request and sth more here)
  }, 700);

  $('input').unbind('keyup keypress').on('keyup keypress', debounced);

For checking "Enter" button is pressed, I need to check event.keyCode || event.which event.keyCode || event.which and call the flush method inside the debounce function definition.

  const debounced = _.debounce((event) => {
    if (13 === (event.keyCode || event.which)) return debounced.flush();

    // Call ajax request and sth more here)
  }, 700);

But it seems the request still delay and did not be called.

Since debounced would invoke the callback function only 700ms after the last time it was called, the enter check would also be applied only 700ms after you pressed enter.

Create an event handler that calls debounced , and flushes it if enter is pressed.

 const debounced = _.debounce(value => { console.log(value); }, 700); const eventHandler = e => { if (e.key === 'Enter') return debounced.flush(); debounced(e.target.value); } $('input').on('keyup keypress', eventHandler);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <input>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM