javascriptreactjssettimeoutweb-workerthread-sleep

How to ensure user logout with Web Worker when the computer goes to sleep


I’m using a Web Worker to set a setTimeout that automatically logs out the user after 10 minutes of inactivity. However, I’ve encountered an issue where if the user’s computer goes to sleep, all processes, including the Web Worker, stop running. This means that even if the session should have expired, the user remains logged in when the computer wakes up.

Is there a way to ensure that the user is logged out even if the computer goes to sleep and wakes up later? How can I handle this situation effectively?

Any suggestions or solutions would be greatly appreciated!


Solution

  • How about recording the time the user leaves the web and logs out if the time is more than 10 minutes?

    let blurTime;
    
    window.onblur = function() {
        blurTime = Date.now();
    };
    
    window.onfocus = function() {
        const focusTime = Date.now();
        const timeDifference = focusTime - blurTime;
    
        if (timeDifference > 10 * 60 * 1000) {
            logoutUser();
        }
    };