In this article, we will create a webpage that redirects to another page if the user is idle for more than one minute. We will use JavaScript to redirect the web page to another web page if the user is ideal for 10 seconds.
Approach: To make this, we will use setTimeout() and clearTimeout() methods. The setTimeout() method is used to start the countdown for the ideal time and loads to another webpage when the countdown reaches 10 seconds. But if any of the events like clicking the mouse, moving the mouse, or an element is touched by the user (which is observed by the addEventListener function), the clearTimeout() method is called to stop the execution of the setTimeout after which the setTimeout() method restarts its countdown of idle activity from 0 seconds. At the end of 10 seconds, the webpage automatically redirects to the GFG home page.
Syntax:
const resetIdleTimeout = function () { if (idleTimeout) clearTimeout(idleTimeout); idleTimeout = setTimeout( () => location.href = redirectUrl, idleDurationSecs * 1000); }; resetIdleTimeout(); ['click', 'touchstart', 'mousemove'].forEach( evt => document.addEventListener(evt, resetIdleTimeout, false) );
Example: In this example, the web page redirects to another web page if the user idle for 10 Seconds in JavaScript
HTML
<!DOCTYPE html> < html > < head > < title > How to Redirects to Another WebPage if User Idle for 10 Seconds in JavaScript ? </ title > </ head > < body > < h style = "color:green;" > Welcome To GFG </ h > < p >Wait Idle For 10 Seconds To See Magic.</ p > < script > (function () { // Ideal time in seconds const idleDurationSecs = 10; // Redirect idle users to this URL const redirectUrl = // Variable to hold the timeout let idleTimeout; const resetIdleTimeout = function () { // Clears the existing timeout if (idleTimeout) clearTimeout(idleTimeout); // Set a new idle timeout to load the // redirectUrl after idleDurationSecs idleTimeout = setTimeout(() => location.href = redirectUrl, idleDurationSecs * 1000); }; // Init on page load resetIdleTimeout(); // Reset the idle timeout on any of // the events listed below ['click', 'touchstart', 'mousemove'] .forEach(evt => document.addEventListener( evt, resetIdleTimeout, false) ); })(); </ script > </ body > </ html > |
Output: