簡體   English   中英

在用戶離開頁面后運行去抖動的 function

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM