I have a debounced function of 3 seconds that I send off to an API service for tracking events.
// api.js
import { debounce } from 'lodash'
const submitRecords = debounce(async () => {
await API.submit({ ...data })
// do other stuff here
}, 3000)
Every time there's a user interaction, my application calls submitRecords
, waits 3 seconds, and then makes a request to the API service. The problem here is that if the user navigates away before 3 seconds, the call never gets made.
Is there a way to still send the debounced request even when the user has navigated away from the current URL? I read up on window.onbeforeunload
but I'm not sure if it's suitable for my use case.
Yes, you can use window.onbeforeunload
. But instead of async/await
may be you need some another debounce
implementation, or to do it by yourself. It can be done with debounce
implemented by usage setTimeout
and storing timer somewhere globally. In window.onbeforeunload
check timer and if present - execute required logic.
Or you can try to use flag that indicates function in debouncing
. Like:
const isDebouncing = false;
const submitRecords = () => {
isDebouncing = true;
debounce(async () => {
isDebouncing = false;
await API.submit({ ...data })
// do other stuff here
}, 3000)();
}
window.onbeforeunload = () => {
if (isDebouncing) {
// do request
}
}
Note: Besides just one flag you can store another data related to await API.submit({...data })
.
Note: in some cases window.onbeforeunload requires preventing event and return value, like:
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
});
Described her: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
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.