JavaScript 如何在10秒钟内用户空闲时重定向到另一个网页

JavaScript 如何在10秒钟内用户空闲时重定向到另一个网页

在本文中,我们将创建一个网页,如果用户空闲时间超过一分钟,则将重定向到另一个页面。我们将使用JavaScript在用户空闲10秒钟后将网页重定向到另一个网页。

方法: 为此,我们将使用setTimeout()和clearTimeout()方法。setTimeout()方法用于开始倒计时,当倒计时达到10秒时加载到另一个网页。但是,如果用户执行任何事件,如点击鼠标、移动鼠标或触摸元素(通过addEventListener函数观察到),则调用clearTimeout()方法来停止执行setTimeout()方法,然后setTimeout()方法重新开始以0秒的空闲活动倒计时。在10秒钟结束时,网页会自动重定向到GFG主页。

语法:

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)
);

示例: 在这个例子中,如果用户在JavaScript中闲置了10秒钟,网页将重定向到另一个网页。

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 =  
                'https://www.geeksforgeeks.org/'; 
              
            // 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>

输出:

JavaScript 如何在10秒钟内用户空闲时重定向到另一个网页

将下面的英文翻译成中文,不解释,保留HTML格式:

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程