lodash debounce not working in anonymous function

后端 未结 5 1358
忘了有多久
忘了有多久 2020-12-08 18:08

Hello I cannot seem to figure out why the debounce function works as expected when passed directly to a keyup event; but it does not work if I wrap it inside an anonymous fu

5条回答
  •  长情又很酷
    2020-12-08 18:47

    debounce doesn't execute the function, it returns a function with the debounciness built into it.

    Returns

    (Function): Returns the new debounced function.

    So your #function handler is actually doing the Right Thing, by returning a function to be used by jQuery as a keyup handler. To fix your #noReturnAnonFunction example, you could simply execute the debounced function in the context of your function:

    $('#noReturnAnonFunction').on('keyup', function () {
        _.debounce(debounceIt, 500, false)(); // Immediately executes
    });
    

    But that's introducing a needless anonymous function wrapper around your debounce.

提交回复
热议问题