sindresorhus / debounce

Delay function calls until a set time elapses after the last invocation
Other
798 stars 80 forks source link

Run debounced callback when browser tab is closed #39

Closed h closed 1 year ago

h commented 1 year ago

A common issue with debounced API calls is that when the user closes the browser tab, the debounced function may not have run yet. This is a frequent cause of data loss. This issue is now fixed by running the trailing debounce immediately if the tab is closed prior to the trailing timeout.

The code detects whether it's running in an environment with access to the DOM. In runtimes where it's unavailable (e.g. Node.js) the new functionality is ignored since would not be relevant in that context.

Fixes #38 @stephenmathieson

sindresorhus commented 1 year ago

I agree that this is outside the scope of this package. I don't even think it's correct to assume that users always want this behavior. And visibilitychange is not just emitted on tab close.