bjoerge / debounce-promise

Create a debounced version of a promise returning function
MIT License
241 stars 27 forks source link

Don't call function later if leading is true #24

Open saltire opened 5 years ago

saltire commented 5 years ago

When I set leading: true, I'd expect the function to only be called when it is actually triggered.

Consider a typing indicator for a chat application. I'd like to send the indicator event as soon as the user starts typing, and resend it if they are still typing after every 5 seconds. Currently, if they start typing and stop after 2 seconds, it will send an event on the leading edge (good), then queue the remaining events and send a second one at the end of 5 seconds, even though by then the user isn't typing anymore.

With leading: true, does it make sense to expect all events that can't be sent on the leading edge to be ignored? If there are good use cases to the contrary, would it make sense to add an option to accommodate both?

saltire commented 5 years ago

There's a second issue with this use case: the 5 second timeout seems to count from the last time the event was triggered, rather than the last time it was run. So if the user types for 12 seconds, an event gets fired right away, then again about 5 seconds after the user finishes typing, i.e. 17 seconds after they started. Should that be expected?

Tofandel commented 3 years ago

Yeah that's different from what is expected, it's missing a trailing option to control that behavior, so that if the debounce is called within the wait time, it should resolve from the first call and not be called later on

I updated this package and published it under @tofandel/debounce-promise I'll make a PR

ivangreene commented 3 months ago

The docs lay out this expectation accordingly: https://github.com/bjoerge/debounce-promise#with-leadingtrue

The first return value is the value of the first invocation, immediately, and all subsequent are resolved with the last value, after the delay.

This may be more appropriate for cases like e.g autosaving a form. It can happen instantly, but we also want to capture the very last call so we don't lose data