Automatic Logout after 10 minutes of inactive in JavaScript

Automatic Logout after 10 minutes of inactive in JavaScript

If you want to destroy session if users are not doing any kind of activity on website. At that time after specific time users should automatically redirect on logout or index page.

How to redirect on logout page after 10 minutes of no activity? Here is solution for you just copy and past below code and enjoy.

Note: Change Variable value: redirectUrl = ‘Your redirect URL’;

(function() {
    const idleDurationSecs = 900;
    const redirectUrl = 'Redirect Page URL';
    let idleTimeout;

    const resetIdleTimeout = function() {
        if(idleTimeout) clearTimeout(idleTimeout);
        idleTimeout = setTimeout(() => location.href = redirectUrl, idleDurationSecs * 1000);
	// Key events for reset time
    window.onmousemove = resetIdleTimeout;
    window.onkeypress = resetIdleTimeout; = resetIdleTimeout;
    window.onclick = resetIdleTimeout;
    window.touchstart = resetIdleTimeout;
    window.onfocus = resetIdleTimeout;
    window.onchange = resetIdleTimeout;
    window.onmouseover = resetIdleTimeout;
    window.onmouseout = resetIdleTimeout;
    window.onmousemove = resetIdleTimeout;
    window.onmousedown = resetIdleTimeout;
    window.onmouseup = resetIdleTimeout;
    window.onkeypress = resetIdleTimeout;
    window.onkeydown = resetIdleTimeout;
    window.onkeyup = resetIdleTimeout;
    window.onsubmit = resetIdleTimeout;
    window.onreset = resetIdleTimeout;
    window.onselect = resetIdleTimeout;
    window.onscroll = resetIdleTimeout;

About Author

My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.