From a988237eb43fe0b68465c4c965f869b51d0c60ea Mon Sep 17 00:00:00 2001
From: wxiaoguang <wxiaoguang@gmail.com>
Date: Tue, 30 Apr 2024 23:35:42 +0800
Subject: [PATCH] Improve logout from worker (#30775)

A quick fix for #30756
---
 web_src/js/features/notification.js | 3 ++-
 web_src/js/features/stopwatch.js    | 3 ++-
 web_src/js/modules/worker.js        | 9 +++++++++
 3 files changed, 13 insertions(+), 2 deletions(-)
 create mode 100644 web_src/js/modules/worker.js

diff --git a/web_src/js/features/notification.js b/web_src/js/features/notification.js
index 2de640e6742..8e5a1f83db8 100644
--- a/web_src/js/features/notification.js
+++ b/web_src/js/features/notification.js
@@ -1,6 +1,7 @@
 import $ from 'jquery';
 import {GET} from '../modules/fetch.js';
 import {toggleElem} from '../utils/dom.js';
+import {logoutFromWorker} from '../modules/worker.js';
 
 const {appSubUrl, notificationSettings, assetVersionEncoded} = window.config;
 let notificationSequenceNumber = 0;
@@ -95,7 +96,7 @@ export function initNotificationCount() {
           type: 'close',
         });
         worker.port.close();
-        window.location.href = `${appSubUrl}/`;
+        logoutFromWorker();
       } else if (event.data.type === 'close') {
         worker.port.postMessage({
           type: 'close',
diff --git a/web_src/js/features/stopwatch.js b/web_src/js/features/stopwatch.js
index bcea26bd6e7..79d9892b748 100644
--- a/web_src/js/features/stopwatch.js
+++ b/web_src/js/features/stopwatch.js
@@ -1,6 +1,7 @@
 import {createTippy} from '../modules/tippy.js';
 import {GET} from '../modules/fetch.js';
 import {hideElem, showElem} from '../utils/dom.js';
+import {logoutFromWorker} from '../modules/worker.js';
 
 const {appSubUrl, notificationSettings, enableTimeTracking, assetVersionEncoded} = window.config;
 
@@ -77,7 +78,7 @@ export function initStopwatch() {
           type: 'close',
         });
         worker.port.close();
-        window.location.href = `${appSubUrl}/`;
+        logoutFromWorker();
       } else if (event.data.type === 'close') {
         worker.port.postMessage({
           type: 'close',
diff --git a/web_src/js/modules/worker.js b/web_src/js/modules/worker.js
new file mode 100644
index 00000000000..ef3f1dea483
--- /dev/null
+++ b/web_src/js/modules/worker.js
@@ -0,0 +1,9 @@
+import {sleep} from '../utils.js';
+
+const {appSubUrl} = window.config;
+
+export async function logoutFromWorker() {
+  // wait for a while because other requests (eg: logout) may be in the flight
+  await sleep(5000);
+  window.location.href = `${appSubUrl}/`;
+}