[英]Running a debounced function after user has navigated away from page
我有一个 3 秒的去抖动 function 发送到 API 服务以跟踪事件。
// api.js
import { debounce } from 'lodash'
const submitRecords = debounce(async () => {
await API.submit({ ...data })
// do other stuff here
}, 3000)
每次有用户交互时,我的应用程序都会调用submitRecords
,等待 3 秒,然后向 API 服务发出请求。 这里的问题是,如果用户在 3 秒之前离开,则永远不会进行呼叫。
即使用户已经离开当前的 URL,有没有办法仍然发送去抖动的请求? 我阅读了window.onbeforeunload
但我不确定它是否适合我的用例。
是的,您可以使用window.onbeforeunload
。 但是,您可能需要一些其他的debounce
实现,或者自己做,而不是async/await
。 它可以通过使用setTimeout
实现的debounce
来完成,并将计时器存储在全局某处。 在window.onbeforeunload
检查计时器,如果存在 - 执行所需的逻辑。
或者您可以尝试在 debouncing 中使用指示debouncing
的标志。 喜欢:
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
}
}
注意:除了一个标志之外,您还可以存储与await API.submit({...data })
相关的其他数据。
注意:在某些情况下 window.onbeforeunload 需要阻止事件和返回值,例如:
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
});
描述她: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.