How to detect idle time in JavaScript elegantly?

前端 未结 30 2419
别跟我提以往
别跟我提以往 2020-11-21 11:51

Is it possible to detect \"idle\" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.

Idle time:

30条回答
  •  忘掉有多难
    2020-11-21 12:56

    Debounce actually a great idea! Here version for jQuery free projects:

    const derivedLogout = createDerivedLogout(30);
    derivedLogout(); // it could happen that user too idle)
    window.addEventListener('click', derivedLogout, false);
    window.addEventListener('mousemove', derivedLogout, false);
    window.addEventListener('keyup', derivedLogout, false); 
    
    function createDerivedLogout (sessionTimeoutInMinutes) {
        return _.debounce( () => {
            window.location = this.logoutUrl;
        }, sessionTimeoutInMinutes * 60 * 1000 ) 
    }
    

提交回复
热议问题