0
connectedCallback(){

 this.blurHandler =   () =>   this.testFunction();
 this.beforeUnloadHandler =  () => this.testFunction();

}

I am getting the issue where both of these events the blur and beforeunload run at same time and testFunction is getting called at same time. I am trying to figure out how to get them to only run once the other is finished if they are both called at the same time.

2
  • What does testFunction actually do? What objective are you trying to achieve?
    – sfdcfox
    Commented Apr 9 at 17:45
  • @sfdcfox testFunction makes an api call to update some data. The issue is that both events are happening simultaneously with different data so its updating it incorrectly. I am trying to figure out way whichever is called first the other waits to be called because in the calls i return something that is needed for all future calls
    – James
    Commented Apr 9 at 17:51

1 Answer 1

1

Anything network request not sent by the time beforeunload finishes will never be sent. When both events go off in short succession, you won't have time for the blur event to wait until after the beforeunload event, nor can you delay the beforeunload event itself. The best possible outcome is to have blur wait to see if beforeunload was called. You can do this with a Promise.

this.blurHandler = async () => {
  await Promise.resolve(); 
  this.testFunction();
}
this.beforeUnloadHandler = () => this.testFunction();

As I stated, however, the blur event won't be able to make its API call in this case, because the page has unloaded after beforeunload finishes successfully. Therefore, you may want to store data somewhere that the testFunction can check to see if something needs to be sent:

this.blurHandler = async () => {
  this.dataToSend = something;
  await Promise.resolve(); 
  this.testFunction();
}
this.beforeUnloadHandler = () => this.testFunction();

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .