Underscore debounce vs vanilla Javascript setTimeout

前端 未结 4 2075
有刺的猬
有刺的猬 2021-02-08 19:20

I understand that debounce in Undercore.js returns a function that will postpone its execution until the wait time is over.

My question is, is there an adva

4条回答
  •  北海茫月
    2021-02-08 19:43

    setTimeout and debounce are in no way the same thing. setTimeout simply waits n milliseconds and the invokes the supplied function. debounce on the other hand returns a function that only calls the callback after n milliseconds after the last time the functions was called.

    Huge difference. Debouncing/throttling (they are not the same thing) functions are often used to reduced the amount of function calls as a result of user input. Imagine a autocomplete/typeahead field. You might do an ajax request every keystroke, but that can get kind of heavy, so instead you can debounce the function, so it will only fire 200ms after the last keystroke.

    You can read up on the documentation here: https://lodash.com/docs#debounce

提交回复
热议问题